Тёмный

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

Laravel Daily
Подписаться 141 тыс.
Просмотров 87 тыс.
50% 1

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: • Laravel: When to Use S...
- 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/...
- 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

Хобби

Опубликовано:

 

27 сен 2020

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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!
@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.
@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 Год назад
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.
@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 !
@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 !
@HassanHafeez007
@HassanHafeez007 3 года назад
Much needed lecture on this topic. Thanks
@maksympletiuk5311
@maksympletiuk5311 3 года назад
Awesome! Very informative and understandable. I glad that found your channel)
@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.
@chlouis-girardot
@chlouis-girardot 3 года назад
Just awesome, thanks a lot Sir!
@belce1982
@belce1982 2 года назад
Thanks as always! Learn, learn, learn!
@teddyperera8531
@teddyperera8531 3 года назад
nice and clean explanation. Thank you
@nabeelyousafpasha
@nabeelyousafpasha 3 года назад
Most Left out topic. Thanks you covered it. Respect from Pakistan 🇵🇰
@WastiPlayX
@WastiPlayX 3 года назад
Thank you,you helped me a lot!
@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".
@brunoggdev6305
@brunoggdev6305 Год назад
Amazing content man, thank you!
@aagaleon
@aagaleon 3 года назад
this is extensive knowledge, thank you so much
@ShakirAli-hr7sc
@ShakirAli-hr7sc 2 года назад
Hi sir, It's really smart strong concept logic and very help full, thank you so much.
@user-ri8ow3qh7l
@user-ri8ow3qh7l 2 года назад
You are my best friend, thanks for lessons.
@muhammadtariq7474
@muhammadtariq7474 3 года назад
Always informative!!
@wikumdiluka5159
@wikumdiluka5159 Год назад
Great explanation 👍👍
@Felipe-ez5gg
@Felipe-ez5gg Год назад
this is what i was looking for! :D
@Jameskaguo
@Jameskaguo 3 года назад
I love your tutorials
@cultureofnepal2024
@cultureofnepal2024 3 года назад
One of the best video. 👍👍👍
@fd1c81e7
@fd1c81e7 3 года назад
Great videos great work Thanks sir !
@jeevachaithanyansivanandan
@jeevachaithanyansivanandan 3 года назад
thank you for the helpful info
@debarshidas8678
@debarshidas8678 3 года назад
Thank you for the video.
@anandmalvi1603
@anandmalvi1603 3 года назад
Great Work!!
@aminedaimallah310
@aminedaimallah310 3 года назад
thanks this is really useful
@nameLastname786
@nameLastname786 3 года назад
Good work !
@algeriennesaffaires7017
@algeriennesaffaires7017 3 года назад
Very useful 👍
@moinshaikh6203
@moinshaikh6203 3 года назад
bruh! uh just at the point....love it boy
@bru6626
@bru6626 3 года назад
Ahhh finally !! Thankssss!
@devMoemen
@devMoemen 2 года назад
thank you very much
@shahosanandaji9894
@shahosanandaji9894 2 года назад
Thanks a lot!
@learnlaravel8145
@learnlaravel8145 3 года назад
Thank you sir!
@mohammadrouhani7049
@mohammadrouhani7049 2 года назад
Thank you .
@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 :)
@gayankavinda9757
@gayankavinda9757 5 месяцев назад
thanks you very much
@modestusmunh93
@modestusmunh93 Год назад
Thanks sir!
@AkhileshYadav-lv3kh
@AkhileshYadav-lv3kh 2 года назад
Very good sir 👍 👌👌
@sumonchandrashil8406
@sumonchandrashil8406 3 года назад
Thanks master.
@jeffersoncarvalho2566
@jeffersoncarvalho2566 3 года назад
Do I need to return view in the UserNotFoundExeption and in the catch method ?
@hamzamux6197
@hamzamux6197 3 года назад
gr8 tutorial sir
@ermail_biz
@ermail_biz 3 года назад
really useful
@khanhli974
@khanhli974 3 года назад
tks u for this
@Felipe-ez5gg
@Felipe-ez5gg Год назад
thanks a lot!!!
@RioBahtiar
@RioBahtiar 3 года назад
Thank you :)
@phuoctranngoc8749
@phuoctranngoc8749 3 года назад
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
@jerlabor2518
@jerlabor2518 2 года назад
Hi! Thank you for the vid, but I can't see the link about services.
@theprof1129
@theprof1129 Год назад
Wonderful
@overLordOrigin
@overLordOrigin 3 года назад
very good
@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
@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
@TheEmberEve
@TheEmberEve Месяц назад
return view is also in controller and in render method, which one will work?
@andreich1980
@andreich1980 3 года назад
What about render method in the new Exception class? Why don't you use it instead of rendering the view manually?
@selzwawy4181
@selzwawy4181 2 года назад
Nice
@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] ); }
@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?
@ssupercrack
@ssupercrack 2 года назад
Thanks, crack!
@vincolasrj
@vincolasrj 3 года назад
You can use the helper report($e) inside catch block to make laravel log the error...
@bewildstudio
@bewildstudio 3 года назад
nice)
@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 ?
@awansaif
@awansaif 3 года назад
Sir, I have a problem in laravel 8 that when I change user profile with default sittings its not working.;
@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?
@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
@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.
@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.
@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.
@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.
@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
@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 🙏🏻. ❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️
@hassantariq1243
@hassantariq1243 3 года назад
ALLAH bless you. Really help full Keep it up Sir!
@ventures9560
@ventures9560 3 года назад
ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-RTTXZVIL6tw.html ^ 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 ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-RTTXZVIL6tw.html 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 :)
@hieuvongoc6114
@hieuvongoc6114 3 года назад
ah shit i don't insert "\" before exeption
@cali4484
@cali4484 3 года назад
php artisan make:like --comment
@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.
Далее
HOW DID SHE WIN??
00:49
Просмотров 16 млн
Optimizing Eloquent: Running Out Of Memory?
6:11
Просмотров 42 тыс.
Refactor "Senior" PHP Code with Early Returns
12:09
Просмотров 26 тыс.
Laravel: The BEST way to handle exceptions
9:29
Просмотров 14 тыс.
Two Things Laravel Services Should NOT Do
8:20
Просмотров 21 тыс.
9 Tips for Shorter Laravel Code
10:16
Просмотров 61 тыс.
Don't throw exceptions in C#. Do this instead
18:13
Просмотров 251 тыс.
Laravel Service Error: Abort or Throw Exceptions?
6:11