Laravel: Avoid Try-Catch In Every Method (What To Do Instead)

  Рет қаралды 28,777

Laravel Daily

Laravel Daily

10 ай бұрын

I want to show you a non-ideal try-catch-exception approach some developers take and how to globally override the exceptions in the Laravel exception handler.
Links mentioned in the video:
- The original Laracasts topic: laracasts.com/discuss/channel...
- Laravel Docs for Error Handling: laravel.com/docs/10.x/errors#...
- Our course "Handling Exceptions and Errors in Laravel": laraveldaily.com/course/excep...
- - - - -
Support the channel by checking out my products:
- My Laravel courses: laraveldaily.com/courses
- Laravel QuickAdminPanel: quickadminpanel.com
- Livewire Kit Components: livewirekit.com
- - - - -
Other places to follow:
- My weekly Laravel newsletter: us11.campaign-archive.com/hom...
- My personal Twitter: / povilaskorop

Пікірлер: 27
@webdev8659
@webdev8659 10 ай бұрын
With amazing accuracy, Pavillas talks about what I need today. Do you have a crystal ball? When will the course "Predictions"? "A personal horoscope for a developer"?
@VKLuc
@VKLuc 10 ай бұрын
Following is my approach. Exceptions are (as their name implies) something that happens exceptionally on the server side. Therefore my approach is to 1. Use a global exception handler. 2. Log all the details on the server 3. Send a meaningful message to the user, explaining what is expected from the user. This should include whether the action may be retried or not and a 'reference id' of the details logged at the server. Never should the message to the user expose the internal workings of the application (such as database errors). Exposing server details is both meaningless and insecure. Situations like validations errors on user input should not be handled via exceptions, as they are not exceptional and fit into a normal request/response behavior. Br, Luc
@noisevector
@noisevector 10 ай бұрын
Technically Laravel uses a ValidationException for validation errors.
@rsgjunior99
@rsgjunior99 10 ай бұрын
I completely agree with point 1 and 2. But I think stating that exceptions should not be used to handle validation errors is too extreme. Your system expects certain parameters, if it doesn't receive, well, that's an exceptional case. As Pavillas said, it´s important to create your own types of Exception to be able to diferenciate those cases and not do the same treatment as a default Exception. This can help simplify and centralize error handling. In Laravel i don't think it's necessary as you have better ways of doing those validations with the FormRequest classes.
@adarshchacko6137
@adarshchacko6137 10 ай бұрын
@VKLuc How do you go about sending a meaningful message to the user? Do you have a condition inside the global exception handler ?
@rsgjunior99
@rsgjunior99 10 ай бұрын
@@adarshchacko6137 You can have multiple catch blocks catching different types of exception. For example: try { //code... } catch (YourSystemException $e) { // send response using $e->getMessage(). This is safe because you know only your system throws this exception. // you can do other stuff trough the exception object, like defining a HTTP Status code. } catch (Throwable $th) { // send response with a generic message }
@VKLuc
@VKLuc 10 ай бұрын
@@adarshchacko6137 No. Usually I create a custom exception type that is reportable. In its constructor the custom exception type takes the real exception that occurred. In the report and render methods the custom exception type decides what info to send to the logging (report method)and what info to send to the user (render method). It also allocates a reference id for the exception. I often use a uuid that is written to the logging system and shown to the user. (e.g. 'you can contact the helpdesk with reference xxx-xxxx-xxxx) The only thing to change in the standard global exception handler is the logic to rethrow each exception as a custom exception. public function register(): void { $this->reportable(function (Throwable $e) { throw(new MyCustomException($e)); }); }
@stunext
@stunext 10 ай бұрын
My approach is to add a render method on my exceptions, so I don't have a huge exception handler. Laravel uses the render method of my exceptions or I use try/catch if needed
@bbbbburton
@bbbbburton 5 ай бұрын
The best way to bring your exceptions under control is using @throws annotation with PHPStan (or Larastan if using Laravel). You are then forced to document or handle your exceptions at the right level, or let them bubble up past your controller and to the handler.
@devstackdemystified
@devstackdemystified 10 ай бұрын
Thanks a lot good stuff big bro!
@SussanRai
@SussanRai 10 ай бұрын
Try catch in only controller method but in some cases try catch is used in service layer for certain purpose.
@emekatimothyiloba699
@emekatimothyiloba699 10 ай бұрын
Thanks sir❤
@tomasfigura4385
@tomasfigura4385 10 ай бұрын
I use try catch so I can put a breakpoint when debugging into the catch part and then I can read error message when error happens.
@mauldoto
@mauldoto 5 ай бұрын
Yeah, i use try catch to and throw the error with spesific message
@NanaYaw
@NanaYaw 10 ай бұрын
I use DB transactions in my controller methods and in the catch block, rollback on any kind of exception. What do I do in this case if you advise not to use try catch in controller methods
@amitsolanki9363
@amitsolanki9363 4 ай бұрын
Do you find any solution for this?
@mahmoud-bakheet
@mahmoud-bakheet 10 ай бұрын
I'm not good in errors handling but i looking my classes where they meet especially when i use services class then i make exception
@someone-jq3lc
@someone-jq3lc 10 ай бұрын
what if I want to use DB::transaction() in controller how to combine that with exception handling globally
@SXsoft99
@SXsoft99 3 ай бұрын
public function update() { DB::beginTransation(); try { // queries go here DB::commit(); }catch (\Exception $e){ DB::rollback(); Log::error($e); return error; } return success; }
@kailasbedarkar7197
@kailasbedarkar7197 6 ай бұрын
laravel try catch sometime it has "Exception" OR "Throwable". Is there any difference between them?
@JuniorTripod
@JuniorTripod 5 ай бұрын
Yes, in throwable includes errors, not only exceptions, like TypeError or FatalError. Both exceptions and error implements Throwable interface, so you can catch an error or exception.
@johnnyw525
@johnnyw525 13 күн бұрын
Exception classes were made for... EXCEPTIONS. Things that your program is not expected to handle! And you're not supposed to misuse exceptions to hide bugs -- you need them to blow up in a big way. It's the whole point of them: If there's a problem with the system, it should be fixed. Not hidden! And Exceptions should be LOGGED. The user is not expected to deal with them, you, the devs, is! Error codes are for YOU, not the user!
@igerardogc
@igerardogc 10 ай бұрын
What theme editor is it? Its very clean and readable, how can i get ur .editorconfig?
@LaravelDaily
@LaravelDaily 10 ай бұрын
PhpStorm Material Darker.
Junior Code Review: Laravel Routes, Middleware, Validation and more
19:57
Middleware in nextjs | Nextjs fullstack course
41:39
Hitesh Choudhary
Рет қаралды 39 М.
버블티로 체감되는 요즘 물가
00:16
진영민yeongmin
Рет қаралды 88 МЛН
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01
Khó thế mà cũng làm được || How did the police do that? #shorts
01:00
JAVA: 'Final' Keyword
2:47
Mindtek
Рет қаралды 22
Exceptions in Laravel: Why/How to Use and Create Your Own
12:18
Laravel Daily
Рет қаралды 86 М.
14 Quick Laravel Tips in 9 Minutes: May 2024
9:09
Laravel Daily
Рет қаралды 9 М.
Laravel: The BEST way to handle exceptions
9:29
Przemysław Przyłucki
Рет қаралды 14 М.
Static Methods in Laravel/PHP: When and How?
10:39
Laravel Daily
Рет қаралды 16 М.
Why is Laravel NOT used in Big Development Projects?
11:53
Stefan Mischook
Рет қаралды 170 М.
I respect children #respect #respectshorts
0:34
Movie Copy
Рет қаралды 10 МЛН
Dekho Anaya Ne Kaise Mnaya Apna Birthday 🎂🎉
0:46
Anaya Kandhal
Рет қаралды 46 МЛН
Невестка с приколом 😱
0:23
ТРЕНДИ ШОРТС
Рет қаралды 3,8 МЛН
Think of stray animals 🙏😥
0:37
Ben Meryem
Рет қаралды 58 МЛН