What Is HTTP Exceptions Handling In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 18-09-2020

Exceptions are used to change the normal flow of a script if a specified error occurs.

What Is HTTP Exceptions Handling In Laravel With Example

Some exceptions describe HTTP error codes from the server. For example, this may be a "page not found" error (404), an "unauthorized error" (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort helper:
 

abort(404);


The abort helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:

abort(403, 'Unauthorized action.');


Custom HTTP Error Pages

Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable:
 

<h2>{{ $exception->getMessage() }}</h2>


You may publish Laravel's error page templates using the vendor:publish Artisan command. Once the templates have been published, you may customize them to your liking:
 

php artisan vendor:publish --tag=laravel-errors


Always throw a tailored exception and then handle the conversion within the controller. In this case wrap it in a HttpException. There are a few good reasons for this:

  • The decision on which status code and message is delegated to the implementation (in this case the integration with your framework). This means that you could drop your code in any framework and handle its errors separately.
  • You decide you need a CLI command/worker and now your HttpException throws in your service make no sense to your CLI command.

Essentially thinking about a calculator, it would throw a DivisionByZeroException. For a controller you would wrap this in a HttpException 400 BAD REQUEST and re-throw. For the CLI your command could just let the exception render on screen Division By ZeroEither way this decision is not made by your service.


To know more about Exceptions Error Handling visit Bajarangisoft site.

Related Post