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

แชร์
ฝัง
  • เผยแพร่เมื่อ 16 ม.ค. 2025
  • 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/do...
    - - - -
    Support the channel by checking out my products:
    My Laravel courses membership: laraveldaily.t...
    Laravel QuickAdminPanel: bit.ly/quickad...
    Livewire Kit Components: livewirekit.com
    - - - -
    Other places to follow:
    My weekly Laravel newsletter: bit.ly/laravel-...
    My personal Twitter: / povilaskorop

ความคิดเห็น • 119

  • @ДмитрийЕгорычев-д9ъ
    @ДмитрийЕгорычев-д9ъ 4 ปีที่แล้ว +31

    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 4 ปีที่แล้ว

      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.

  • @vickymistry7442
    @vickymistry7442 3 ปีที่แล้ว +8

    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.

  • @MichaelBrown-vq4fd
    @MichaelBrown-vq4fd 4 ปีที่แล้ว +4

    Thank you for this. As a beginner I was struggling with how to catch and throw exceptions.

  • @psyick9543
    @psyick9543 3 ปีที่แล้ว +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 4 ปีที่แล้ว

    you pretty much covered all about exceptions in 12 minutes, hats off

  • @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 !

  • @vincej151
    @vincej151 4 ปีที่แล้ว +2

    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 !

  • @SergiuBurduja-y1l
    @SergiuBurduja-y1l 3 ปีที่แล้ว

    You are my best friend, thanks for lessons.

  • @wikumdiluka5159
    @wikumdiluka5159 2 ปีที่แล้ว

    Great explanation 👍👍

  • @HamidAliOfficial
    @HamidAliOfficial 4 ปีที่แล้ว +9

    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 4 ปีที่แล้ว +15

      Good point, no need for try catch then, forgot to mention it in the video.

    • @nikza1936
      @nikza1936 3 ปีที่แล้ว +1

      laravel.com/docs/8.x/errors#renderable-exceptions
      public function render($request)
      {
      $error=$this->getMessage();
      return view(' 'someview ', ['error'=>$error] );
      }

  • @maksympletiuk5311
    @maksympletiuk5311 4 ปีที่แล้ว +1

    Awesome! Very informative and understandable. I glad that found your channel)

  • @sarmadsaqlain740
    @sarmadsaqlain740 2 ปีที่แล้ว +1

    Sir you are just awesome, exactly what I was looking for! 👍

  • @nabeelyousafpasha
    @nabeelyousafpasha 4 ปีที่แล้ว

    Most Left out topic. Thanks you covered it. Respect from Pakistan 🇵🇰

  • @HassanHafeez007
    @HassanHafeez007 4 ปีที่แล้ว

    Much needed lecture on this topic. Thanks

  • @jeffersoncarvalho2566
    @jeffersoncarvalho2566 4 ปีที่แล้ว +2

    Do I need to return view in the UserNotFoundExeption and in the catch method ?

  • @ShakirAli-hr7sc
    @ShakirAli-hr7sc 2 ปีที่แล้ว

    Hi sir, It's really smart strong concept logic and very help full, thank you so much.

  • @ravindujeewhantha4012
    @ravindujeewhantha4012 4 ปีที่แล้ว

    what an excellent tutorial. Thank you sir and please do more tutorials. Thank you gain.

  • @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".

  • @algeriennesaffaires7017
    @algeriennesaffaires7017 3 ปีที่แล้ว

    Very useful 👍

  • @cultureofnepal2024
    @cultureofnepal2024 4 ปีที่แล้ว

    One of the best video. 👍👍👍

  • @WastiPlayX
    @WastiPlayX 4 ปีที่แล้ว +1

    Thank you,you helped me a lot!

  • @anluwagePH
    @anluwagePH 3 ปีที่แล้ว

    this is extensive knowledge, thank you so much

  • @teddyperera8531
    @teddyperera8531 4 ปีที่แล้ว

    nice and clean explanation. Thank you

  • @belce1982
    @belce1982 3 ปีที่แล้ว

    Thanks as always! Learn, learn, learn!

  • @brunoggdev6305
    @brunoggdev6305 2 ปีที่แล้ว

    Amazing content man, thank you!

  • @thevipinchand4690
    @thevipinchand4690 4 ปีที่แล้ว

    As always great explanation. Thank you

  • @parisnakitakejser
    @parisnakitakejser 4 ปีที่แล้ว

    Thanks a lot for this video, its help me to understand how its working inside Laravel, keep up the good work :)

  • @chlouis-girardot
    @chlouis-girardot 4 ปีที่แล้ว +1

    Just awesome, thanks a lot Sir!

  • @jerlabor2518
    @jerlabor2518 3 ปีที่แล้ว

    Hi! Thank you for the vid, but I can't see the link about services.

  • @AkhileshYadav-lv3kh
    @AkhileshYadav-lv3kh 2 ปีที่แล้ว

    Very good sir 👍 👌👌

  • @debarshidas8678
    @debarshidas8678 3 ปีที่แล้ว

    Thank you for the video.

  • @Shez-dc3fn
    @Shez-dc3fn 3 ปีที่แล้ว +1

    if you have quite a few models, are you suggesting we have a sep. exception for each entity i.e. {entity}NotFoundException

    • @edphogi5513
      @edphogi5513 3 ปีที่แล้ว

      i have same question.. anyone?

    • @LaravelDaily
      @LaravelDaily  3 ปีที่แล้ว

      No, totally not, should be a general NotFoundException with probably a different message, or different action in "catch" section of try-catch.

  • @adarshchacko6137
    @adarshchacko6137 2 ปีที่แล้ว

    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.

  • @andreich1980
    @andreich1980 3 ปีที่แล้ว +1

    What about render method in the new Exception class? Why don't you use it instead of rendering the view manually?

  • @pwcodigo
    @pwcodigo 4 หลายเดือนก่อน

    Bom dia. No exemplo 8:22 o senhor usar ModelFoundException. O ModelFoundException ele executado apenas quando a model não existir ? No caso, a model existi mas não existi o dado na tabela username, se ele der problema é por causa do first e não porque a model não existe do ModelFoundException , correto ?

  • @jeevachaithanyansivanandan
    @jeevachaithanyansivanandan 3 ปีที่แล้ว

    thank you for the helpful info

  • @inf2004
    @inf2004 4 ปีที่แล้ว +2

    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 4 ปีที่แล้ว +1

      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 4 ปีที่แล้ว

      @@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 4 ปีที่แล้ว +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 4 ปีที่แล้ว

      @@PovilasKorop Understood. Thanks for your answer and excellent videos.

  • @TheEmberEve
    @TheEmberEve 7 หลายเดือนก่อน

    return view is also in controller and in render method, which one will work?

  • @PutolevePetitliph
    @PutolevePetitliph 4 ปีที่แล้ว +1

    What code editor is that you are using?

    • @PovilasKorop
      @PovilasKorop 4 ปีที่แล้ว +1

      PhpStorm.

    • @PutolevePetitliph
      @PutolevePetitliph 4 ปีที่แล้ว

      @@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

  • @Felipe-ez5gg
    @Felipe-ez5gg 2 ปีที่แล้ว

    this is what i was looking for! :D

  • @noushedakib1658
    @noushedakib1658 2 หลายเดือนก่อน

    Thank You

  • @Jameskaguo
    @Jameskaguo 4 ปีที่แล้ว

    I love your tutorials

  • @zakariabenali4447
    @zakariabenali4447 3 ปีที่แล้ว +1

    Is it a good practice to handle and catche all exceptions in Handle.php file ? this way you can make controller a lot cleaner

  • @aminedaimallah310
    @aminedaimallah310 4 ปีที่แล้ว

    thanks this is really useful

  • @longingheart77
    @longingheart77 4 ปีที่แล้ว +1

    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 4 ปีที่แล้ว +1

      That would not be one video, it would be a series of videos on different topics :)

  • @kudashevs
    @kudashevs 3 ปีที่แล้ว

    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  3 ปีที่แล้ว

      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 3 ปีที่แล้ว +1

      ​@@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.

  • @mohammadrouhani7049
    @mohammadrouhani7049 2 ปีที่แล้ว

    Thank you .

  • @devMoemen
    @devMoemen 3 ปีที่แล้ว

    thank you very much

  • @fd1c81e7
    @fd1c81e7 3 ปีที่แล้ว

    Great videos great work Thanks sir !

  • @sumonchandrashil8406
    @sumonchandrashil8406 3 ปีที่แล้ว

    Thanks master.

  • @shahosanandaji9894
    @shahosanandaji9894 3 ปีที่แล้ว

    Thanks a lot!

  • @vincolasrj
    @vincolasrj 4 ปีที่แล้ว +2

    You can use the helper report($e) inside catch block to make laravel log the error...

  • @muhammadtariq7474
    @muhammadtariq7474 4 ปีที่แล้ว

    Always informative!!

  • @moinshaikh6203
    @moinshaikh6203 3 ปีที่แล้ว

    bruh! uh just at the point....love it boy

  • @learnlaravel8145
    @learnlaravel8145 3 ปีที่แล้ว

    Thank you sir!

  • @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 ?

  • @khanhli974
    @khanhli974 3 ปีที่แล้ว

    tks u for this

  • @phuoctranngoc8749
    @phuoctranngoc8749 3 ปีที่แล้ว

    Thanks sir

  • @vidhyaprakash85
    @vidhyaprakash85 4 ปีที่แล้ว

    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

  • @nameLastname786
    @nameLastname786 3 ปีที่แล้ว

    Good work !

  • @AbedAbugozah
    @AbedAbugozah ปีที่แล้ว

    But how the server know that the UserNotFounException is for User model and for model not found exception?
    because it extend the exception ?

  • @Felipe-ez5gg
    @Felipe-ez5gg 2 ปีที่แล้ว

    thanks a lot!!!

  • @awansaif
    @awansaif 4 ปีที่แล้ว

    Sir, I have a problem in laravel 8 that when I change user profile with default sittings its not working.;

  • @theprof1129
    @theprof1129 2 ปีที่แล้ว

    Wonderful

  • @overLordOrigin
    @overLordOrigin 4 ปีที่แล้ว

    very good

  • @anandmalvi1603
    @anandmalvi1603 4 ปีที่แล้ว

    Great Work!!

  • @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.

  • @ermail_biz
    @ermail_biz 4 ปีที่แล้ว

    really useful

  • @hamzamux6197
    @hamzamux6197 3 ปีที่แล้ว

    gr8 tutorial sir

  • @a-ezzat5677
    @a-ezzat5677 4 ปีที่แล้ว

    may I ask you a favor,, how to display a pdf and add a signature and barcode then export it again as pdf

  • @RioBahtiar
    @RioBahtiar 4 ปีที่แล้ว

    Thank you :)

  • @bumblebity2902
    @bumblebity2902 4 ปีที่แล้ว

    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 4 ปีที่แล้ว

      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.

  • @msdeav
    @msdeav 4 ปีที่แล้ว

    Is there any easier way than trying and catching in every method of every controller?

    • @PovilasKorop
      @PovilasKorop 4 ปีที่แล้ว

      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 4 ปีที่แล้ว

      @@PovilasKorop Wau. Thank you so much. And for your videos too. There are great...

  • @alila3883
    @alila3883 3 ปีที่แล้ว

    Thx

  • @CyanidePierce90
    @CyanidePierce90 4 ปีที่แล้ว

    How can you catch it if you use route model binding?

    • @PovilasKorop
      @PovilasKorop 4 ปีที่แล้ว +1

      You don't. Route model binding throws ModelNotFoundException automatically.

  • @amitsolanki9363
    @amitsolanki9363 11 หลายเดือนก่อน

    How can i catch post size too large exception in laravel

  • @sanderos4181
    @sanderos4181 3 ปีที่แล้ว

    Nice

  • @ahmedofali
    @ahmedofali 2 ปีที่แล้ว

    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

  • @bru6626
    @bru6626 4 ปีที่แล้ว

    Ahhh finally !! Thankssss!

  • @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?

  • @hassantariq1243
    @hassantariq1243 4 ปีที่แล้ว

    ALLAH bless you. Really help full Keep it up Sir!

  • @easyvideott7505
    @easyvideott7505 4 ปีที่แล้ว +2

    I've seen you doing this multiple times th-cam.com/video/RTTXZVIL6tw/w-d-xo.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 4 ปีที่แล้ว +2

      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 :)

  • @ventures9560
    @ventures9560 4 ปีที่แล้ว

    th-cam.com/video/RTTXZVIL6tw/w-d-xo.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 4 ปีที่แล้ว

      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).

  • @TechnoTrace
    @TechnoTrace 4 ปีที่แล้ว

    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 🙏🏻.
    ❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️❤️

  • @hieuvongoc6114
    @hieuvongoc6114 4 ปีที่แล้ว

    ah shit i don't insert "\" before exeption

  • @dominiks5318
    @dominiks5318 2 ปีที่แล้ว +1

    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.

  • @cali4484
    @cali4484 3 ปีที่แล้ว

    php artisan make:like --comment

  • @ssupercrack
    @ssupercrack 2 ปีที่แล้ว

    Thanks, crack!

  • @gayankavinda9757
    @gayankavinda9757 11 หลายเดือนก่อน

    thanks you very much

  • @modestusmunh93
    @modestusmunh93 2 ปีที่แล้ว

    Thanks sir!