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"?
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
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 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 }
@@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)); }); }
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.
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
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.
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
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
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.
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!
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"?
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
Technically Laravel uses a ValidationException for validation errors.
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.
@VKLuc How do you go about sending a meaningful message to the user? Do you have a condition inside the global exception handler ?
@@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
}
@@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));
});
}
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.
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
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.
Yeah, i use try catch to and throw the error with spesific message
Try catch in only controller method but in some cases try catch is used in service layer for certain purpose.
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.
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
Do you find any solution for this?
Thanks a lot good stuff big bro!
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
laravel try catch sometime it has "Exception" OR "Throwable". Is there any difference between them?
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.
what if I want to use DB::transaction() in controller how to combine that with exception handling globally
public function update()
{
DB::beginTransation();
try {
// queries go here
DB::commit();
}catch (\Exception $e){
DB::rollback();
Log::error($e);
return error;
}
return success;
}
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
Thanks sir❤
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!
What theme editor is it? Its very clean and readable, how can i get ur .editorconfig?
PhpStorm Material Darker.