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:
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 Zero
. Either way this decision is not made by your service.
To know more about Exceptions Error Handling visit Bajarangisoft site.