Error Handling | Laravel - Error Handling
What is Error handling in Laravel?
- Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.
- Specialized programs, called error handlers, are available for some applications.
- The best programs of this type forestall errors if possible, recover from them when they occur without terminating the application, or (if all else fails) gracefully terminate an affected application and save the error information to a log file.
- In Laravel all the exceptions are handled by app\Exceptions\Handler class.
- This class contains two methods - report and render.
laravel , laravel framework , laravel documentation , laravel tutorial , laravel install , laracasts
report() method
- report() method is used to report or log exception.
- It is also used to send log exceptions to external services like Sentry, Bugsnag etc.
- By default, the report method simply passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.
- For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof comparison operator:
render() method
- render() method is used to render an exception into an HTTP response which will be sent back to browser.
- Beside these two methods, the app\Exceptions\Handler class contains an important property called “$dontReport”.
- This property takes an array of exception types that will not be logged.
laravel , laravel framework , laravel documentation , laravel tutorial , laravel install , laracasts
HTTP Exceptions:
- Some exceptions describe HTTP error codes like 404, 500 etc.
- To generate such response anywhere in an application, you can use abort() method as follows.
- The abort helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
Custom Error pages:
- Laravel makes it very easy for us to use the custom error pages for each separate error codes.
- For example, if you want to design custom page for error code 404, you can create a view at resources/views/errors/404.blade.php.
- Same way, if you want to design error page for error code 500, it should be stored at resources/views/errors/500.blade.php.
Example:
- Step 1 − Add the following lines in app/Http/routes.php.
- Step 2 − Create a view file called resources/views/errors/404.blade.phpand copy the following code in that file.
- Step 3 − Visit the following URL to test the event. http://localhost:8000/error
- Step 4 − After visiting the URL, you will receive the following output −