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

  Рет қаралды 35,469

Laravel Daily

Laravel Daily

Күн бұрын

Пікірлер: 29
@VKLuc
@VKLuc Жыл бұрын
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 Жыл бұрын
Technically Laravel uses a ValidationException for validation errors.
@rsgjunior99
@rsgjunior99 Жыл бұрын
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 Жыл бұрын
@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 Жыл бұрын
@@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 Жыл бұрын
@@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)); }); }
@webdev8659
@webdev8659 Жыл бұрын
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"?
@bbbbburton
@bbbbburton 11 ай бұрын
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.
@stunext
@stunext Жыл бұрын
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
@tomasfigura4385
@tomasfigura4385 Жыл бұрын
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 10 ай бұрын
Yeah, i use try catch to and throw the error with spesific message
@SussanRai
@SussanRai Жыл бұрын
Try catch in only controller method but in some cases try catch is used in service layer for certain purpose.
@pwcodigo
@pwcodigo 3 ай бұрын
Que insight. Estou resolvendo esse problema. Eu tenho service e deixa tudo try catch dentro das minhas classes Services. Agora estou passando para controle e alguns casos eu estou colocando usando try catch dentro do service quando me conecto a uma api externa usando macro http do laravel.
@NanaYaw
@NanaYaw Жыл бұрын
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 9 ай бұрын
Do you find any solution for this?
@someone-jq3lc
@someone-jq3lc Жыл бұрын
what if I want to use DB::transaction() in controller how to combine that with exception handling globally
@SXsoft99
@SXsoft99 8 ай бұрын
public function update() { DB::beginTransation(); try { // queries go here DB::commit(); }catch (\Exception $e){ DB::rollback(); Log::error($e); return error; } return success; }
@devstackdemystified
@devstackdemystified Жыл бұрын
Thanks a lot good stuff big bro!
@kailasbedarkar7197
@kailasbedarkar7197 11 ай бұрын
laravel try catch sometime it has "Exception" OR "Throwable". Is there any difference between them?
@JuniorTripod
@JuniorTripod 10 ай бұрын
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.
@JamesAutoDude
@JamesAutoDude 3 ай бұрын
I mostly do try catch when more than one table. If it's just 1 table then I don't bother When I do make try catches, I use descriptive errors for each one too
@mahmoud-bakheet
@mahmoud-bakheet Жыл бұрын
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
@emekatimothyiloba699
@emekatimothyiloba699 Жыл бұрын
Thanks sir❤
@johnnyw525
@johnnyw525 5 ай бұрын
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 Жыл бұрын
What theme editor is it? Its very clean and readable, how can i get ur .editorconfig?
@LaravelDaily
@LaravelDaily Жыл бұрын
PhpStorm Material Darker.
Refactor "Senior" PHP Code with Early Returns
12:09
Laravel Daily
Рет қаралды 27 М.
Exceptions in Laravel: Why/How to Use and Create Your Own
12:18
Laravel Daily
Рет қаралды 88 М.
Accompanying my daughter to practice dance is so annoying #funny #cute#comedy
00:17
Funny daughter's daily life
Рет қаралды 28 МЛН
Don’t Choose The Wrong Box 😱
00:41
Topper Guild
Рет қаралды 51 МЛН
How Many Balloons To Make A Store Fly?
00:22
MrBeast
Рет қаралды 189 МЛН
Smart Sigma Kid #funny #sigma
00:33
CRAZY GREAPA
Рет қаралды 36 МЛН
Google announces Gemini 2.0 - The multi-agentic era is here! (Tested)
13:57
Разбор Error Handling в Laravel. Под капотом Laravel
25:50
Просто о Web Development. CutCode
Рет қаралды 2,5 М.
How To Build Feature Flags Like A Senior Dev In 20 Minutes
20:33
Web Dev Simplified
Рет қаралды 104 М.
Top 5 Laravel "Bad Practices" (My Opinion)
10:32
Laravel Daily
Рет қаралды 24 М.
The Tools I Use to Build Products in Laravel
19:00
Josh Cirre
Рет қаралды 41 М.
Junior Code Review: Laravel Routes, Middleware, Validation and more
19:57
Laravel Security: Top 7 Mistakes Developers Make
11:16
Laravel Daily
Рет қаралды 87 М.
Authorization in Laravel: Can You Do That?
8:29
Laravel
Рет қаралды 10 М.
14 Quick Laravel Tips in 9 Minutes: May 2024
9:09
Laravel Daily
Рет қаралды 11 М.
Accompanying my daughter to practice dance is so annoying #funny #cute#comedy
00:17
Funny daughter's daily life
Рет қаралды 28 МЛН