Exceptions in Laravel: Why/How to Use and Create Your Own

  Рет қаралды 86,825

Laravel Daily

3 жыл бұрын

I see a lot of developers not using Exception classes and try-catch blocks because they don't understand how they actually work under the hood. So, let's learn with an example.
Links mentioned in the video:
- Laravel: When to Use Static Methods, Services, and Dependency Injection: kzbin.info/www/bejne/p2GbiWqXaruZnqc
- Official docs: Error Handling in Laravel laravel.com/docs/8.x/errors
- - - - -
Support the channel by checking out my products:
- My Laravel courses membership: laraveldaily.teachable.com/p/all-courses-yearly-membership?
- Laravel QuickAdminPanel: bit.ly/quickadminpanel
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: bit.ly/laravel-newsletter
- My personal Twitter: povilaskorop

Пікірлер: 118
@MichaelBrown-vq4fd
@MichaelBrown-vq4fd 3 жыл бұрын
Thank you for this. As a beginner I was struggling with how to catch and throw exceptions.
@psyick9543
@psyick9543 2 жыл бұрын
I’ve watched a few of your vids (and subbed) and just want to say you’re a great teacher and I love how you focus on things that can be immediately applied to improve my projects. Thanks!
@user-db3ne9yi3k
@user-db3ne9yi3k 3 жыл бұрын
I think this is much easier to do. The main error handler catches the ModelNotFoundException -> get the model class -> show view. 1. The logic for catching errors is not in the controller or services, but in the handler. You don't need to use try-catch in your code, errors are still passed to the handler. All logic in one place. If you need something special, you can use custom exceptions, the logic for them can also be placed either in the handler or inside the exception. I do not understand why you need to catch errors not in controllers or services
@_passby5399
@_passby5399 3 жыл бұрын
Hi there. Can you explain more about that, or is there any references that I can read on? Thanks.
@turcoalv
@turcoalv 2 жыл бұрын
Please explain, Intresting point of view
@rezaseohamimohajer2736
@rezaseohamimohajer2736 Жыл бұрын
I agree with you
@GutoCmtt
@GutoCmtt 11 ай бұрын
I think the idea here is that you can have the same standard exception meaning different things and needing different treatments in different places. Here it was good to take a general ModelNotFoundException and instead throw a UserNotFoundException, so that you can handle it in a different way. Basically, ModelNotFoundException can be a lot of different stuff, and for each one of them you may want to report or render different things. I think this is why you catch and throw in controllers/services in this case, so that you may specify and treat them accordingly.
@bashardlaleh2110
@bashardlaleh2110 3 жыл бұрын
you pretty much covered all about exceptions in 12 minutes, hats off
@vickymistry7442
@vickymistry7442 2 жыл бұрын
Hello sir. Your content is so much meaningful & I'm following you since 2 week ago. Thanks a lot such a beautiful content. It's very helpful to implement in my live projects.
@vincej151
@vincej151 3 жыл бұрын
Excellent Tutorial!! For some reason, I find your tutorial much easier to follow than those of Jeffrey Way. Often he goes much too fast. Thank you !
@HassanHafeez007
@HassanHafeez007 3 жыл бұрын
Much needed lecture on this topic. Thanks
@maksympletiuk5311
@maksympletiuk5311 3 жыл бұрын
Awesome! Very informative and understandable. I glad that found your channel)
@deazlylol
@deazlylol 3 жыл бұрын
not knowing English I understood everything he was talking about. Thank you so much for helping my problem ! I subscribe to your channel.Thanks a lot !
@sarmadsaqlain740
@sarmadsaqlain740 2 жыл бұрын
Sir you are just awesome, exactly what I was looking for! 👍
@thevipinchand4690
@thevipinchand4690 3 жыл бұрын
As always great explanation. Thank you
@pnk
@pnk 3 жыл бұрын
Thanks a lot for this video, its help me to understand how its working inside Laravel, keep up the good work :)
@ravindujeewhantha4012
@ravindujeewhantha4012 3 жыл бұрын
what an excellent tutorial. Thank you sir and please do more tutorials. Thank you gain.
@belce1982
@belce1982 2 жыл бұрын
Thanks as always! Learn, learn, learn!
@chlouis-girardot
@chlouis-girardot 3 жыл бұрын
Just awesome, thanks a lot Sir!
@nabeelyousafpasha
@nabeelyousafpasha 3 жыл бұрын
Most Left out topic. Thanks you covered it. Respect from Pakistan 🇵🇰
@aagaleon
@aagaleon 3 жыл бұрын
this is extensive knowledge, thank you so much
@dfordemo981
@dfordemo981 2 жыл бұрын
Very very awesome and Informative video for a beginner like me. This helped me a lot. Kindly make a short video on "accessors and mutators".
@teddyperera8531
@teddyperera8531 3 жыл бұрын
nice and clean explanation. Thank you
@user-ri8ow3qh7l
@user-ri8ow3qh7l 2 жыл бұрын
You are my best friend, thanks for lessons.
@brunoggdev6305
@brunoggdev6305 Жыл бұрын
Amazing content man, thank you!
@ShakirAli-hr7sc
@ShakirAli-hr7sc 2 жыл бұрын
Hi sir, It's really smart strong concept logic and very help full, thank you so much.
@muhammadtariq7474
@muhammadtariq7474 3 жыл бұрын
Always informative!!
@WastiPlayX
@WastiPlayX 3 жыл бұрын
Thank you,you helped me a lot!
@Jameskaguo
@Jameskaguo 3 жыл бұрын
I love your tutorials
@Felipe-ez5gg
@Felipe-ez5gg Жыл бұрын
this is what i was looking for! :D
@wikumdiluka5159
@wikumdiluka5159 Жыл бұрын
Great explanation 👍👍
@anandmalvi1603
@anandmalvi1603 3 жыл бұрын
Great Work!!
@cultureofnepal2024
@cultureofnepal2024 3 жыл бұрын
One of the best video. 👍👍👍
@fd1c81e7
@fd1c81e7 3 жыл бұрын
Great videos great work Thanks sir !
@debarshidas8678
@debarshidas8678 3 жыл бұрын
Thank you for the video.
@jeevachaithanyansivanandan
@jeevachaithanyansivanandan 3 жыл бұрын
thank you for the helpful info
@nameLastname786
@nameLastname786 3 жыл бұрын
Good work !
@aminedaimallah310
@aminedaimallah310 3 жыл бұрын
thanks this is really useful
@bru6626
@bru6626 3 жыл бұрын
Ahhh finally !! Thankssss!
@algeriennesaffaires7017
@algeriennesaffaires7017 3 жыл бұрын
Very useful 👍
@moinshaikh6203
@moinshaikh6203 3 жыл бұрын
bruh! uh just at the point....love it boy
@longingheart77
@longingheart77 3 жыл бұрын
Hey thanks for providing us with helpful pieces of advise everyday :) I've been wondering if you could shoot a video where you talk about different stacks that come with using laravel and when to use them (Inertia + jetstream, different ways to authenticate SPAs like Sanctum or oAuth etc)
@PovilasKorop
@PovilasKorop 3 жыл бұрын
That would not be one video, it would be a series of videos on different topics :)
@learnlaravel8145
@learnlaravel8145 3 жыл бұрын
Thank you sir!
@shahosanandaji9894
@shahosanandaji9894 2 жыл бұрын
Thanks a lot!
@modestusmunh93
@modestusmunh93 Жыл бұрын
Thanks sir!
@ermail_biz
@ermail_biz 3 жыл бұрын
really useful
@RioBahtiar
@RioBahtiar 3 жыл бұрын
Thank you :)
@sumonchandrashil8406
@sumonchandrashil8406 3 жыл бұрын
Thanks master.
@Felipe-ez5gg
@Felipe-ez5gg Жыл бұрын
thanks a lot!!!
@AkhileshYadav-lv3kh
@AkhileshYadav-lv3kh 2 жыл бұрын
Very good sir 👍 👌👌
@devMoemen
@devMoemen 2 жыл бұрын
thank you very much
@mohammadrouhani7049
@mohammadrouhani7049 2 жыл бұрын
Thank you .
@hamzamux6197
@hamzamux6197 3 жыл бұрын
gr8 tutorial sir
@gayankavinda9757
@gayankavinda9757 4 ай бұрын
thanks you very much
@theprof1129
@theprof1129 Жыл бұрын
Wonderful
@overLordOrigin
@overLordOrigin 3 жыл бұрын
very good
@khanhli974
@khanhli974 3 жыл бұрын
tks u for this
@phuoctranngoc8749
@phuoctranngoc8749 2 жыл бұрын
Thanks sir
@vidhyaprakash85
@vidhyaprakash85 3 жыл бұрын
With this example which view will be loaded whether view specified in the controller or in the exception. If from the exception then we can remove the view in controller
@selzwawy4181
@selzwawy4181 2 жыл бұрын
Nice
@jeffersoncarvalho2566
@jeffersoncarvalho2566 3 жыл бұрын
Do I need to return view in the UserNotFoundExeption and in the catch method ?
@ssupercrack
@ssupercrack 2 жыл бұрын
Thanks, crack!
@jerlabor2518
@jerlabor2518 2 жыл бұрын
Hi! Thank you for the vid, but I can't see the link about services.
@adarshchacko6137
@adarshchacko6137 Жыл бұрын
Is there a way to keep all the exceptions in the BaseController and later on use it in different controllers? To ensure that the controllers remain clean.
@alila3883
@alila3883 3 жыл бұрын
Thx
@HamidAliOfficial
@HamidAliOfficial 3 жыл бұрын
if we have a custom exception e.g. usernotfound where we have render option do we still need to try and catch and return a view?
@PovilasKorop
@PovilasKorop 3 жыл бұрын
Good point, no need for try catch then, forgot to mention it in the video.
@nikza1936
@nikza1936 3 жыл бұрын
laravel.com/docs/8.x/errors#renderable-exceptions public function render($request) { $error=$this->getMessage(); return view(' 'someview ', ['error'=>$error] ); }
@inf2004
@inf2004 3 жыл бұрын
Hello, Povilas! Thanks for great video! Unfortunately you did not mention app/Exceptions/Handler.php, while in Laravel documentation this class definitely has main role in error handling... It's not clear how to use it, please make part 2 for this video...
@PovilasKorop
@PovilasKorop 3 жыл бұрын
That's actually my style of explaining the topics - to talk about how to use stuff practically, and not how it works under the hood. If you do want to find out about Laravel internal Handler and how it works, I won't explain it better than this page: laravel.com/docs/8.x/errors What exactly is not clear on how to use it? To me, it is explained in a few examples on that page.
@inf2004
@inf2004 3 жыл бұрын
@@PovilasKorop Thanks for your answer... First, it's not clear how to properly catch fatal errors in app/Exceptions/Handler.php, and, for example, send email notification with fatal error description... Second a little confusing thing, is your phrase that handling exceptions improves code readability... No doubt it's right, but on recent job interview, while talking about exceptions, they mainly asked how to handle different types of errors, on which types of errors does script stops, and other error related questions. Unfortunately, they didn't explain why are they asking about that. So now I’m going to suspect that main purpose of "Errors & Logging" Laravel documentation chapter and of using exceptions, is not just improving code readability, but something more...
@PovilasKorop
@PovilasKorop 3 жыл бұрын
@@inf2004 well the whole topic is indeed much deeper, and it's not even about Laravel, it starts with PHP errors and exceptions (and these are different), also types of errors (error, warning, notice etc) and only then php exceptions, and only then Laravel logic on top. So I agree I could talk much deeper on that, but my goal on this channel is to give the most practical lessons in short videos, and not hours of lectures about theory. For that, there's always documentation, books, courses and longer tutorials.
@inf2004
@inf2004 3 жыл бұрын
@@PovilasKorop Understood. Thanks for your answer and excellent videos.
@zakariabenali4447
@zakariabenali4447 3 жыл бұрын
Is it a good practice to handle and catche all exceptions in Handle.php file ? this way you can make controller a lot cleaner
@andreich1980
@andreich1980 3 жыл бұрын
What about render method in the new Exception class? Why don't you use it instead of rendering the view manually?
@TheEmberEve
@TheEmberEve Ай бұрын
return view is also in controller and in render method, which one will work?
@vincolasrj
@vincolasrj 3 жыл бұрын
You can use the helper report($e) inside catch block to make laravel log the error...
@bewildstudio
@bewildstudio 3 жыл бұрын
nice)
@rihulfaakbar2261
@rihulfaakbar2261 Жыл бұрын
I always checking if data I retrieved from database is available or not before using it and display custom message for it, is it readable fo another programmer that way?
@awansaif
@awansaif 3 жыл бұрын
Sir, I have a problem in laravel 8 that when I change user profile with default sittings its not working.;
@a-ezzat5677
@a-ezzat5677 3 жыл бұрын
may I ask you a favor,, how to display a pdf and add a signature and barcode then export it again as pdf
@TheHolyReality
@TheHolyReality 3 жыл бұрын
why would you define same view in the render method of custom exception and in the catch block? whats the point of writing it twice ?
@kudashevs
@kudashevs 2 жыл бұрын
Hello Mr. Polivas, Thank you very much for your channel and for the great content you’ve been providing to us :) I have a question, and it’s a little bit specific. At 5:45 you change `$exceptions->getMessage()` to `get_class($exception)`. At exactly 5:47 you press some hotkey and it highlights the whole `->getMessage()`. Could you please reveal how you did it? Is it a default Intellij hotkey or a custom one? Would you mind making a video with your Intellij setups, and some useful tips and tricks on its usage (with commands, hotkeys, and other useful stuff that you use on a regular basis). I haven’t found such a video on your channel.
@LaravelDaily
@LaravelDaily 2 жыл бұрын
Some of the things are happening during the editing of the video, maybe it was a cut to make the video shorter. I don't have anything specific set up in my phpstorm, it's the defaults.
@kudashevs
@kudashevs 2 жыл бұрын
​@@LaravelDaily it doesn't seem to me that there are any cuts in this place. Let me please rephrase this question and make it less vague. And I need to clarify that by highlight I mean to select. What combination of keys have you pressed to get PHPStorm automatically select the whole method call on the `$exception` variable? The code was: dd($exception->getMessage()). You made a decision to wrap the variable with the get_class() function. You typed get_class() before the `$exception` variable, then you deleted the closing `get_class` parenthesis, and then you pressed something and the whole `->getMessage()` on the $exception variable became selected. And then you deleted this selection with one key, as we usual do. It happens at 5:46 - 5:47. I've tried to do the same step by step, using different keys which I know, but without any result. UP: I rewatched that moment several times and it seems that it was a cut after all. But this possibility to change a code that way looks so cool to me that I obviously need to think about how to realize such a functionality, through macros or something similar :) Anyways, thank you very much for your answer.
@ahmedofali
@ahmedofali Жыл бұрын
I expect If I'm going to handle all exceptions on try and catch I use depend on the contract which is thrawable not \Exception and import it
@AbedAbugozah
@AbedAbugozah 5 ай бұрын
But how the server know that the UserNotFounException is for User model and for model not found exception? because it extend the exception ?
@Shez-dc3fn
@Shez-dc3fn 2 жыл бұрын
if you have quite a few models, are you suggesting we have a sep. exception for each entity i.e. {entity}NotFoundException
@edphogi5513
@edphogi5513 2 жыл бұрын
i have same question.. anyone?
@LaravelDaily
@LaravelDaily 2 жыл бұрын
No, totally not, should be a general NotFoundException with probably a different message, or different action in "catch" section of try-catch.
@petritmekuli
@petritmekuli 2 жыл бұрын
Can models, in this case UserModel, throw new UserNotFoundException(custom exception) instead of ModelNotFoundException when findOrFail doesn't find any model? I think a solution would be overriding the findOrFail() method within the UserModel to throw UserNotFoundException instead, if that's possible. But is there any better solution? Anyone?
@atulnaik2696
@atulnaik2696 3 жыл бұрын
hey I am trying to generate custom responses for my exceptions but they are getting rendered in default way. watched this video 7,8 times dont know if I am missing something.please help.
@bumblebity2902
@bumblebity2902 3 жыл бұрын
So, it's better to do custom not found exception for every model than do general ModelNotFoundException message/response in handler class. Also, how to refactor exception handling in Vue, because I handle errors with general ModelNotFoundException response in handler class.
@PovilasKorop
@PovilasKorop 3 жыл бұрын
It's not better or worse, it depends on what is your goal. For Vue, it plays not with exception classes, but with status codes like 404.
@amitsolanki9363
@amitsolanki9363 5 ай бұрын
How can i catch post size too large exception in laravel
@PutolevePetitliph
@PutolevePetitliph 3 жыл бұрын
What code editor is that you are using?
@PovilasKorop
@PovilasKorop 3 жыл бұрын
PhpStorm.
@PutolevePetitliph
@PutolevePetitliph 3 жыл бұрын
@@PovilasKorop thanks for both the name and the tutorial.. Very helpful, I'm one of the culprits that just dumps try catch without understanding whats happening.lol
@CyanidePierce90
@CyanidePierce90 3 жыл бұрын
How can you catch it if you use route model binding?
@PovilasKorop
@PovilasKorop 3 жыл бұрын
You don't. Route model binding throws ModelNotFoundException automatically.
@msdeav
@msdeav 3 жыл бұрын
Is there any easier way than trying and catching in every method of every controller?
@PovilasKorop
@PovilasKorop 3 жыл бұрын
I'm not saying you should use try-catch everywhere - only when it's actually clear that some kind of exception may appear, and you know/expect it.
@msdeav
@msdeav 3 жыл бұрын
@@PovilasKorop Wau. Thank you so much. And for your videos too. There are great...
@TechnoTrace
@TechnoTrace 3 жыл бұрын
I use this on each of my projects.. Really love seeing a programming God use those techniques as well.. I'm very excited about the things laravel offers. I wanna learn all features and become a super expert on it. If someone has full knowledge of laravel and how it works then he should be super super proud of him as he is a programming God. Povilas, can I ask you something?? Is it possible for Taylor Orwell to develop Laravel on his own?? Or is it possible for someone to make a framework better than laravel. I mean laravel updates, right! So it means that isn't perfect. Nothing is perfect! So can something be much much better than laravel???? You're much more ahead in experience than me, so you can better tell me about it😁❤️❤️ Love to hear from you 🙏🏻🙏🏻❤️❤️❤️❤️❤️ I'm from India. We show respect by 🙏🏻. ❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️
@ventures9560
@ventures9560 3 жыл бұрын
kzbin.info/www/bejne/iIW3iY2MfrFpqtk ^ on line 17 there is a $exception variable. What is that variable connected to? I tried to find it in the other file: UserServices.php but it was not in that file. This seems to be a pattern with this framework. There's always some oddball thing that you can't find a connection in the code to where it is coming from. If anyone can explain what that variable is connected to (as seen in the video on line 17 at the link in this post) I would really appreciate the help. Thanks Jake
@ventures9560
@ventures9560 3 жыл бұрын
Nevermind - I see it. I was going to just delete this but maybe someone else gets the same question some day and it helps them. The answer is that the $exception variable is created on the line above (line 16), then used in the next line (line 17).
@easyvideott7505
@easyvideott7505 3 жыл бұрын
I've seen you doing this multiple times kzbin.info/www/bejne/iIW3iY2MfrFpqtk Just set the cursor before the line you want to move (or make a selection) and hold CTRL + SHIFT + Arrow Up Or Arrow Down to move the code where you want it...
@PovilasKorop
@PovilasKorop 3 жыл бұрын
Thanks for the tip, this is the way I can see someone actually WATCHING my videos :) P.S. On my old Macbook 2015, which I use for shooting videos, the Down Arrow is almost not working, so I'm trying to avoid it :)
@hassantariq1243
@hassantariq1243 3 жыл бұрын
ALLAH bless you. Really help full Keep it up Sir!
@cali4484
@cali4484 3 жыл бұрын
php artisan make:like --comment
@hieuvongoc6114
@hieuvongoc6114 3 жыл бұрын
ah shit i don't insert "\" before exeption
@dominiks5318
@dominiks5318 Жыл бұрын
sorry but this time you've shown VERY BAD approach. Why? Let me explain quickly - I saw dozens of controller methods catching exceptions like that which mostly leads to: codue duplication, bloats the controllers unnecessarily, and most important - it doesnt give you the stacktrace in the message, so developer looking at the logs will have to look for that particular message and if it's repeated among like 10 controllers it's waste of time. Much BETTER approach is to catch those in the Laravel Exception Handler class which is desinged for this.
⬅️🤔➡️
00:31
Celine Dept
Рет қаралды 52 МЛН
NERF WAR HEAVY: Drone Battle!
00:30
MacDannyGun
Рет қаралды 30 МЛН
THEY WANTED TO TAKE ALL HIS GOODIES 🍫🥤🍟😂
00:17
OKUNJATA
Рет қаралды 10 МЛН
Невестка с приколом 😱
0:23
ТРЕНДИ ШОРТС
Рет қаралды 4,1 МЛН
Random pink food asmr mukbang 📱 #asmr #mukbang #eating #food
0:14
how to make a dratti dratte making #viral #dratti #dratte
0:15
offical Blacksmith
Рет қаралды 34 МЛН
Skateboarding Down the Steps
0:11
Ryan's World
Рет қаралды 12 МЛН