HTTP Exception And Error Handling In Laravel

An exception is an unusual event while executing a software program or an application. An Http Exception is the most basic type of web-based exception, so it can be used for many general purposes that relate to something going wrong when processing an HTTP request in an web application.

According to laravel official documentation here, Some exception describe http error code from the server. Such error may be page not found 404 error or something like 500 internal server error.

Generally, we can see these exception while sending request to the server. Server may respond with different kind of error response. We can display custom error page to show what is going wrong in the server.

Default location of error pages is resources/views/errors/ directory. In this directory, we can create page with status code as name and then .blade.php as extension. Laravel application renders corresponding view file based on type of error. We can create files for different status code like following.

  1. 404.blade.php for Page Not Found Error
  2. 500.blade.php for Internal Server Error
  3. 503.blade.php for Service Unavailable Error
  4. 403.blade.php for Forbidden Error

We can create files like above to show error page for each kind of error. 404 error occurs when requested page is not available in the server. 500 error corresponds to error encountered in the server while processing request. 403 error corresponds to error while accessing Unauthorized service. When service is not available 503 error occurs. In Laravel, when application is in maintenance mode, 503 error will occur.

Maintenance Mode In Laravel

Generating Custom Exceptions

We can generate these errors programmatically as well using abort helper function. This function takes status code, error message and header array as optional parameter. We can generate such errors like this:

Above function is useful when we want to generate exception for custom purpose. Let’s take an example, Request wants an employee with id 100 but it doesn’t exist in the database. In this case, we can generate custom 404 error with our message like this

Laravel provides easy way to display the message generated during custom error generation. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.

getMessage function returns the error generated by abort function. We can easily use above code to display our own message in the error page.



Computer Enginner, A Laravel Developer,

Leave a Reply

Your email address will not be published. Required fields are marked *