Version
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Reporting Exceptions
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. 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 reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
Note
To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Exception Log Levels
When messages are written to your application’s logs, the messages are written at a specified log level, which indicates the severity or importance of the message being logged.
As noted above, even when you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at.
To accomplish this, you may define an array of exception types and their associated log levels within the $levels
property of your application’s exception handler:
use PDOException;
use PsrLogLogLevel;
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<Throwable>, PsrLogLogLevel::*>
*/
protected $levels = [
PDOException::class => LogLevel::CRITICAL,
];
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
InvalidOrderException::class,
];
Note
Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(/* ... */);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
Note
You may type-hint any required dependencies of thereport
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
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);
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
view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException
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 default 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
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
Laravel sends error exceptions mail, this tutorial shows you how you can send error exceptions on developer mail. Here you will learn to send error exceptions on developer mail or as you want any other mail.
If you have deployed your larval application on a live server. Your live laravel app is running fine. If there were no issues with the laravel application. Sometimes, major error exceptions came for your laravel app. The app will be down and the user will leave your application
In Laravel, all exceptions are handled by the AppExceptionsHandler
class. This class contains two methods: report
and render
.
Laravel sends an error exception to mail steps
In some cases, what if you were immediately informed via e-mail (or any other service) about the bug and you fix it ASAP. In Laravel, this can be done easily. We will learn how to send error exceptions mail step by step in this post.
We are going to show you how you can send error exception mail in your laravel app. Just follow the few steps and it has finished.
- Create Mail Class
- Create an Email View
- Send Error Exception Mail
Create Mail Class
First of all, create a mail class using the below command:
php artisan make:mail ExceptionMail
This will create a class ExceptionMail in the app/Mail
directory.
<?php namespace AppMail; use IlluminateBusQueueable; use IlluminateMailMailable; use IlluminateQueueSerializesModels; use IlluminateContractsQueueShouldQueue; class ExceptionMail extends Mailable { use Queueable, SerializesModels; /** * The body of the message. * * @var string */ public $content; /** * Create a new message instance. * * @return void */ public function __construct($content) { $this->content = $content; } /** * Build the message. * * @return $this */ public function build() { return $this->view('emails.exception_email') ->with('content', $this->content); } }
Create Email View
Now, we will create a new view file inside the emails folder that file name email_exception.blade.php. and the below-given code in add your email_exception.blade.php file:
Send Error Exception Mail
Go to AppExceptionsHandler file and update the below code into your file.
<?php namespace AppExceptions; use Mail; use SymfonyComponentDebugExceptionFlattenException; use SymfonyComponentDebugExceptionHandler as SymfonyExceptionHandler; use AppMailExceptionOccured; use Exception; use IlluminateFoundationExceptionsHandler as ExceptionHandler; class Handler extends ExceptionHandler { /** * A list of the exception types that are not reported. * * @var array */ protected $dontReport = [ // ]; /** * A list of the inputs that are never flashed for validation exceptions. * * @var array */ protected $dontFlash = [ 'password', 'password_confirmation', ]; /** * Report or log an exception. * * @param Exception $exception * @return void */ public function report(Exception $exception) { if ($this->shouldReport($exception)) { $this->sendEmail($exception); // sends an email } parent::report($exception); } /** * Render an exception into an HTTP response. * * @param IlluminateHttpRequest $request * @param Exception $exception * @return IlluminateHttpResponse */ public function render($request, Exception $exception) { return parent::render($request, $exception); } public function sendEmail(Exception $exception) { try { $e = FlattenException::create($exception); $handler = new SymfonyExceptionHandler(); $html = $handler->getHtml($e); Mail::to('[email protected]')->send(new ExceptionMail($html)); } catch (Exception $ex) { dd($ex); } } }
In case, error exception is thrown by your application. You will receive an email with full information about the errors.
Conclusion
In this tutorial, you have learned step by step how to send error exceptions mail on laravel application.
If you were immediately informed via e-mail (or any other service) about the bug and you fix it ASAP. In Laravel, this can be done easily. We have learned how to send error exceptions mail step by step in this post.
Thanks to reading this how to send error mail in laravel.
Recommended Laravel Posts
My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.
View all posts by Admin
Версия
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Reporting Exceptions
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. 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 reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
{tip} To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
InvalidOrderException::class,
];
{tip} Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
{tip} You may type-hint any required dependencies of the
report
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
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);
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
view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException
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 default 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
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
You’ve created a new Laravel app for your client and deployed it on the production server. Everything was working fine till a customer has a problem with the app because of some buggy code. He immediately leaves the app, and the same thing happens with multiple customers before you know about the bug. You fix the bug, and then everything is on track.
But what if you were notified immediately through e-mail (or another service) about the bug and you fix it ASAP. In Laravel, this can be done easily and in this post, we’re going to learn how.
In Laravel, all exceptions are handled by the AppExceptionsHandler
class. This class contains two methods: report
and render
. We’re only interested in report
method; it is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method simply passes the exception to the base class where the exception is logged. However, we can use it to send an email to developers about the exception.
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Emails.
*
* @param Exception $exception
* @return void
*/
public function report(Exception $exception)
{
if ($this->shouldReport($exception)) {
$this->sendEmail($exception); // sends an email
}
return parent::report($exception);
}
/**
* Sends an email to the developer about the exception.
*
* @param Exception $exception
* @return void
*/
public function sendEmail(Exception $exception)
{
// sending email
}
Here we are using shouldReport
method to ignore exceptions which are listed in the $dontReport
property of the exception handler.
Each type of email sent by the application is represented as a “mailable” class in Laravel. So, we need to create our mailable class using the make:mail
command:
$ php artisan make:mail ExceptionOccured
This will create a class ExceptionOccured
in the app/Mail
directory.
Merely sending the mail will not solve the problem. We need the full stack trace of the exception. And for that, we can use the Symfony’s Debug component.
public function sendEmail(Exception $exception)
{
try {
$e = FlattenException::create($exception);
$handler = new SymfonyExceptionHandler();
$html = $handler->getHtml($e);
Mail::to('developer@gmail.com')->send(new ExceptionOccured($html));
} catch (Exception $ex) {
dd($ex);
}
}
Make sure you add the following code at the top of the file:
use Mail;
use SymfonyComponentDebugExceptionFlattenException;
use SymfonyComponentDebugExceptionHandler as SymfonyExceptionHandler;
use AppMailExceptionOccured;
Note—We have used the try
block to avoid the infinite loop if the mail command fails.
Then, in your ExceptionOccured
mailer class:
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateContractsQueueShouldQueue;
class ExceptionOccured extends Mailable
{
use Queueable, SerializesModels;
/**
* The body of the message.
*
* @var string
*/
public $content;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($content)
{
$this->content = $content;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.exception')
->with('content', $this->content);
}
}
Add the following code in your emails.exception
view file:
{!! $content !!}
Now, whenever an exception is thrown in your application, you will receive an email with full stack trace. Cool!
I have created a Laravel package named squareboat/sneaker to do all this cumbersome work for you so you can concentrate on solving the bug.
Some of the features of the sneaker are:
– On/off emailing using .env
file.
– Customizing the email body.
– Ignoring the exception generated by bots.
and more to come.
If you want the complete source code for this, I’m more than happy to share it and you can find the source code on Github
Laravel is a powerful and one of the best MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. It facilitates developers by saving huge time and helps reduce thinking and planning to develop the entire website from scratch.
Whenever we are planning to deploy Laravel application on production server, we test aggressively and try to find out bugs that may create nightmare for clients as well as for developers. Once we are done with testing we turn debug/error logs off for display as actual users are never shown the behind process.
Everything was working fine after we deployed app on production server till customer founds a problem while accessing app due to bug and he/she immediately leaves the application. This can happen to multiple customers until app developers found the same bug and resolves it. This can be very bitter experience for customers and the client will be also be not happy with the service provided.
Now just think that if you were notified immediately through e-mail about the bug the very first time any customer faced and you fix it ASAP. Laravel provides this feature to send email whenever error occurs on application so that website downtime is much less and minimum customer faces the issue. Let’s see how to do that in Laravel.
In Laravel application , all exceptions are handled by the AppExceptionsHandler
class which is by default present in your project directory. This class contains two methods: report and
render
. We will only use report
method as it is used to log exceptions and send then to email or any other service. By default, the report method simply passes the exception to the base class where the exception is logged. We will modify this method to send error logs to developer or any other email.
Now I am going to show you how you can send error exception mail in your laravel app. Just follow the below steps and you are ON for receiving error logs on e-mail.
1. Create Mail Class using make:mail command
The below command will create a class ExceptionOccured in the app/Mail
directory.
February 1, 2023
Category : Laravel
I am going to show you example of laravel send email on exception. step by step explain laravel send exception mail. if you have question about how to send mail on exception in laravel then I will give simple example with solution. you can see laravel send email on error.
You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.
Sometimes we upload code on production and when you have any error on production then we don’t know it. Even laravel log on laravel.log file but as a developer, we don’t check every day on the log file. so you need something that will inform you when error or exception generate on your application. I will give you the perfect solution for this. When any error or exception generate in your laravel project then it will inform you via email. Yes, We will send an email on Error Exceptions in laravel.
It’s totally free. So just follow the below step and add send mail on an error in laravel app.
Step 1: Install Laravel
This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Make Configuration
In first step, you have to add send mail configuration with mail driver, mail host, mail port, mail username, mail password so laravel 9 will use those sender configuration for sending email. So you can simply add as like following.
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 3: Create Mail Class
In this step we will create mail class ExceptionOccured for email send on error exception. So let’s run bellow command.
php artisan make:mail ExceptionOccured
now, let’s update code on ExceptionOccured.php file as bellow:
app/Mail/ExceptionOccured.php
<?php
namespace AppMail;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
class ExceptionOccured extends Mailable
{
use Queueable, SerializesModels;
public $content;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($content)
{
$this->content = $content;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->view('emails.exception')
->with('content', $this->content);
}
}
Step 4: Create Blade View
In this step, we will create blade view file for email. In this file we will write all exception details. now we just write some dummy text. create bellow files on «emails» folder.
resources/views/emails/exception.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="robots" content="noindex,nofollow" />
<style> body { background-color: #F9F9F9; color: #222; font: 14px/1.4 Helvetica, Arial, sans-serif; margin: 0; padding-bottom: 45px; }
a { cursor: pointer; text-decoration: none; }
a:hover { text-decoration: underline; }
abbr[title] { border-bottom: none; cursor: help; text-decoration: none; }
code, pre { font: 13px/1.5 Consolas, Monaco, Menlo, "Ubuntu Mono", "Liberation Mono", monospace; }
table, tr, th, td { background: #FFF; border-collapse: collapse; vertical-align: top; }
table { background: #FFF; border: 1px solid #E0E0E0; box-shadow: 0px 0px 1px rgba(128, 128, 128, .2); margin: 1em 0; width: 100%; }
table th, table td { border: solid #E0E0E0; border-width: 1px 0; padding: 8px 10px; }
table th { background-color: #E0E0E0; font-weight: bold; text-align: left; }
.hidden-xs-down { display: none; }
.block { display: block; }
.break-long-words { -ms-word-break: break-all; word-break: break-all; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; }
.text-muted { color: #999; }
.container { max-width: 1024px; margin: 0 auto; padding: 0 15px; }
.container::after { content: ""; display: table; clear: both; }
.exception-summary { background: #B0413E; border-bottom: 2px solid rgba(0, 0, 0, 0.1); border-top: 1px solid rgba(0, 0, 0, .3); flex: 0 0 auto; margin-bottom: 30px; }
.exception-message-wrapper { display: flex; align-items: center; min-height: 70px; }
.exception-message { flex-grow: 1; padding: 30px 0; }
.exception-message, .exception-message a { color: #FFF; font-size: 21px; font-weight: 400; margin: 0; }
.exception-message.long { font-size: 18px; }
.exception-message a { border-bottom: 1px solid rgba(255, 255, 255, 0.5); font-size: inherit; text-decoration: none; }
.exception-message a:hover { border-bottom-color: #ffffff; }
.exception-illustration { flex-basis: 111px; flex-shrink: 0; height: 66px; margin-left: 15px; opacity: .7; }
.trace + .trace { margin-top: 30px; }
.trace-head .trace-class { color: #222; font-size: 18px; font-weight: bold; line-height: 1.3; margin: 0; position: relative; }
.trace-message { font-size: 14px; font-weight: normal; margin: .5em 0 0; }
.trace-file-path, .trace-file-path a { color: #222; margin-top: 3px; font-size: 13px; }
.trace-class { color: #B0413E; }
.trace-type { padding: 0 2px; }
.trace-method { color: #B0413E; font-weight: bold; }
.trace-arguments { color: #777; font-weight: normal; padding-left: 2px; }
@media (min-width: 575px) {
.hidden-xs-down { display: initial; }
}</style>
</head>
<body>
<div class="exception-summary">
<div class="container">
<div class="exception-message-wrapper">
<h1 class="break-long-words exception-message">{{ $content['message'] ?? '' }}</h1>
<div class="exception-illustration hidden-xs-down"></div>
</div>
</div>
</div>
<div class="container">
<div class="trace trace-as-html">
<table class="trace-details">
<thead class="trace-head"><tr><th>
<h3 class="trace-class">
<span class="text-muted">(1/1)</span>
<span class="exception_title"><span title="ErrorException">ErrorException</span></span>
</h3>
<p class="break-long-words trace-message">{{ $content['message'] ?? '' }}</p>
<p class="">URL: {{ $content['url'] ?? '' }}</p>
<p class="">IP: {{ $content['ip'] ?? '' }}</p>
</th></tr></thead>
<tbody>
<tr>
<td>
<span class="block trace-file-path">in <span title="{{ $content['file'] ?? '' }}"><strong>{{ $content['file'] ?? '' }}</strong> line {{ $content['line'] ?? '' }}</span></span>
</td>
</tr>
@foreach(($content['trace'] ?? []) as $value)
<tr>
<td>
at <span class="trace-class"><span title="{{ $value['class'] ?? '' }}">{{ basename($value['class'] ?? '') }}</span></span><span class="trace-type">-></span><span class="trace-method">{{ $value['function'] ?? '' }}</span>(<span class="trace-arguments"></span>)<span class="block trace-file-path">in <span title=""><strong>{{ $value['file'] ?? '' }}</strong> line {{ $value['line'] ?? '' }}</span></span>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</body>
</html>
Step 5: Send Mail on Exception
Here, every error exception handle on Exceptions/Handler.php file in laravel. in this file we will write code for send email with error message, file, line, trace, url and ip address details. you can get more details and send in email.
You can also store this information on database from here. so let’s copy below code and paste on Handler.php file. You need to change recipient email address.
app/Exceptions/Handler.php
<?php
namespace AppExceptions;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use Throwable;
use Log;
use Mail;
use AppMailExceptionOccured;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array>
*/
protected $dontReport = [
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
$this->sendEmail($e);
});
}
/**
* Write code on Method
*
* @return response()
*/
public function sendEmail(Throwable $exception)
{
try {
$content['message'] = $exception->getMessage();
$content['file'] = $exception->getFile();
$content['line'] = $exception->getLine();
$content['trace'] = $exception->getTrace();
$content['url'] = request()->url();
$content['body'] = request()->all();
$content['ip'] = request()->ip();
Mail::to('your_email@gmail.com')->send(new ExceptionOccured($content));
} catch (Throwable $exception) {
Log::error($exception);
}
}
}
Step 6: Create Routes
In this step, we will add one route that generate exception and you will receive one email notification. We are creating this is a testing route. so let’s add it.
routes/web.php
<?php
use IlluminateSupportFacadesRoute;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/get-error', function () {
$find = AppModelsUser::find(100000)->id;
return view('welcome');
});
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:8000/get-error
Output: You Email Look Like This
I hope it can help you…
- Введение
- Конфигурирование
-
Обработчик исключений
- Отчет об исключениях
- Игнорирование исключений по типу
- Отображение исключений
- Отчетные и отображаемые исключения
-
HTTP-исключения
- Пользовательские страницы ошибок HTTP
Введение
Когда вы запускаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. Класс AppExceptionsHandler
– это то место, где все исключения, созданные вашим приложением, регистрируются и затем отображаются пользователю. В этой документации мы углубимся в этот класс.
Конфигурирование
Параметр debug
в конфигурационном файле config/app.php
определяет, сколько информации об ошибке фактически отобразится пользователю. По умолчанию этот параметр установлен, чтобы учесть значение переменной окружения APP_DEBUG
, которая содержится в вашем файле .env
.
Во время локальной разработки вы должны установить для переменной окружения APP_DEBUG
значение true
. Во время эксплуатации приложения это значение всегда должно быть false
. Если в рабочем окружении будет установлено значение true
, вы рискуете раскрыть конфиденциальные значения конфигурации конечным пользователям вашего приложения.
Обработчик исключений
Отчет об исключениях
Все исключения обрабатываются классом AppExceptionsHandler
. Этот класс содержит метод register
, в котором вы можете зарегистрировать свои отчеты об исключениях и замыкания рендеринга. Мы подробно рассмотрим каждую из этих концепций. Отчеты об исключениях используются для регистрации исключений или отправки их во внешнюю службу, например Flare, Bugsnag или Sentry. По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией логирования. Однако вы можете регистрировать исключения как хотите.
Например, если вам нужно сообщать о различных типах исключений по-разному, вы можете использовать метод reportable
для регистрации замыкания, которое должно быть выполнено, когда необходимо сообщить об исключении конкретного типа. Laravel определит о каком типе исключения сообщает замыкание с помощью типизации аргументов:
use AppExceptionsInvalidOrderException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
Когда вы регистрируете собственные замыкания для создания отчетов об исключениях, используя метод reportable
, Laravel по-прежнему регистрирует исключение, используя конфигурацию логирования по умолчанию для приложения. Если вы хотите остановить распространение исключения в стек журналов по умолчанию, вы можете использовать метод stop
при определении замыкания отчета или вернуть false
из замыкания:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
Чтобы настроить отчет об исключениях для переданного исключения, вы можете рассмотреть возможность использования отчетных исключений.
Глобальное содержимое журнала
Если доступно, Laravel автоматически добавляет идентификатор текущего пользователя в каждое сообщение журнала исключения в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context
класса AppExceptionsHandler
вашего приложения. Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:
/**
* Получить переменные контекста по умолчанию для ведения журнала.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Контекст журнала исключений
Хотя добавление контекста в каждое сообщение журнала может быть полезно, иногда конкретное исключение может иметь уникальный контекст, который вы хотели бы включить в свои журналы. Определив метод context
для конкретного исключения вашего приложения, вы можете указать любые данные, относящиеся к этому исключению, которые должны быть добавлены в запись журнала исключения:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Получить контекстную информацию исключения.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
Помощник report
По желанию может потребоваться сообщить об исключении, но продолжить обработку текущего запроса. Помощник report
позволяет вам быстро сообщить об исключении через обработчик исключений, не отображая страницу с ошибкой для пользователя:
public function isValid($value)
{
try {
// Проверка `$value` ...
} catch (Throwable $e) {
report($e);
return false;
}
}
Игнорирование исключений по типу
При создании приложения будут некоторые типы исключений, которые вы просто хотите игнорировать и никогда не сообщать о них. Обработчик исключений вашего приложения содержит свойство $dontReport
, которое инициализируется пустым массивом. Ни о каких классах, добавленных в это свойство, никогда не будет сообщено; однако у них все еще может быть собственная логика отображения:
use AppExceptionsInvalidOrderException;
/**
* Список типов исключений, о которых не следует сообщать.
*
* @var array
*/
protected $dontReport = [
InvalidOrderException::class,
];
За кулисами Laravel уже игнорирует для вас некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 HTTP-ответ, сгенерированный при недопустимом CSRF-токене.
Отображение исключений
По умолчанию обработчик исключений Laravel будет преобразовывать исключения в HTTP-ответ за вас. Однако вы можете зарегистрировать свое замыкание для отображения исключений конкретного типа. Вы можете сделать это с помощью метода renderable
обработчика исключений.
Замыкание, переданное методу renderable
, должно вернуть экземпляр IlluminateHttpResponse
, который может быть сгенерирован с помощью функции response
. Laravel определит, какой тип исключения отображает замыкание с помощью типизации аргументов:
use AppExceptionsInvalidOrderException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
Вы также можете использовать метод renderable
чтобы переопределить отображение для встроенных исключений Laravel или Symfony, таких, как NotFoundHttpException
. Если замыкание, переданное методу renderable
не возвращает значения, будет использоваться отрисовка исключений Laravel по умолчанию:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Зарегистрировать замыкания, обрабатывающие исключения приложения.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Отчетные и отображаемые исключения
Вместо проверки типов исключений в методе register
обработчика исключений вы можете определить методы report
и render
непосредственно для ваших исключений. Если эти методы существуют, то они будут автоматически вызываться фреймворком:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Отчитаться об исключении.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Преобразовать исключение в HTTP-ответ.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
Если ваше исключение расширяет исключение, которое уже доступно для визуализации, например встроенное исключение Laravel или Symfony, вы можете вернуть false
из метода render
исключения, чтобы отобразить HTTP-ответ исключения по умолчанию:
/**
* Преобразовать исключение в HTTP-ответ.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Определить, требуется ли для исключения пользовательское отображение...
return false;
}
Если ваше исключение содержит пользовательскую логику отчетности, которая необходима только при выполнении определенных условий, то вам может потребоваться указать Laravel когда сообщать об исключении, используя конфигурацию обработки исключений по умолчанию. Для этого вы можете вернуть false
из метода report
исключения:
/**
* Сообщить об исключении.
*
* @return bool|null
*/
public function report()
{
// Определить, требуется ли для исключения пользовательская отчетность ...
return false;
}
Вы можете указать любые требуемые зависимости метода
report
, и они будут автоматически внедрены в метод контейнером служб Laravel.
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок с сервера. Например, это может быть ошибка «страница не найдена» (404), «неавторизованный доступ» (401) или даже ошибка 500, сгенерированная разработчиком. Чтобы создать такой ответ из любой точки вашего приложения, вы можете использовать глобальный помощник abort
:
abort(404);
Пользовательские страницы ошибок HTTP
Laravel позволяет легко отображать пользовательские страницы ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов HTTP-состояния 404, создайте файл resources/views/errors/404.blade.php
. Это представление будет отображено для всех ошибок 404, сгенерированных вашим приложением. Шаблоны в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр SymfonyComponentHttpKernelExceptionHttpException
, вызванный функцией abort
, будет передан в шаблон как переменная $exception
:
<h2>{{ $exception->getMessage() }}</h2>
Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel с помощью команды vendor:publish
Artisan. После публикации шаблонов вы можете настроить их по своему вкусу:
php artisan vendor:publish --tag=laravel-errors
Error Handling
- Introduction
- Configuration
- The Exception Handler
- Reporting Exceptions
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
- HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions thrown by your application are logged and then rendered to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
During local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
Reporting Exceptions
All exceptions are handled by the AppExceptionsHandler
class. This class contains a register
method where you may register custom exception reporting and rendering callbacks. We’ll examine each of these concepts in detail. Exception reporting is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, exceptions will be logged based on your logging configuration. 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 reportable
method to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will deduce what type of exception the closure reports by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (InvalidOrderException $e) {
//
});
}
When you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop
method when defining your reporting callback or return false
from the callback:
$this->reportable(function (InvalidOrderException $e) {
//
})->stop();
$this->reportable(function (InvalidOrderException $e) {
return false;
});
Note
To customize the exception reporting for a given exception, you may also utilize reportable exceptions.
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Exception Log Context
While adding context to every log message can be useful, sometimes a particular exception may have unique context that you would like to include in your logs. By defining a context
method on one of your application’s custom exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array
*/
public function context()
{
return ['order_id' => $this->orderId];
}
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception via the exception handler without rendering an error page to the user:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Exception Log Levels
When messages are written to your application’s logs, the messages are written at a specified log level, which indicates the severity or importance of the message being logged.
As noted above, even when you register a custom exception reporting callback using the reportable
method, Laravel will still log the exception using the default logging configuration for the application; however, since the log level can sometimes influence the channels on which a message is logged, you may wish to configure the log level that certain exceptions are logged at.
To accomplish this, you may define an array of exception types and their associated log levels within the $levels
property of your application’s exception handler:
use PDOException;
use PsrLogLogLevel;
/**
* A list of exception types with their corresponding custom log levels.
*
* @var array<class-string<Throwable>, PsrLogLogLevel::*>
*/
protected $levels = [
PDOException::class => LogLevel::CRITICAL,
];
Ignoring Exceptions By Type
When building your application, there will be some types of exceptions you simply want to ignore and never report. Your application’s exception handler contains a $dontReport
property which is initialized to an empty array. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:
use AppExceptionsInvalidOrderException;
/**
* A list of the exception types that are not reported.
*
* @var array<int, class-string<Throwable>>
*/
protected $dontReport = [
InvalidOrderException::class,
];
Note
Behind the scenes, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP «not found» errors or 419 HTTP responses generated by invalid CSRF tokens.
Rendering Exceptions
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering closure for exceptions of a given type. You may accomplish this via the renderable
method of your exception handler.
The closure passed to the renderable
method should return an instance of IlluminateHttpResponse
, which may be generated via the response
helper. Laravel will deduce what type of exception the closure renders by examining the type-hint of the closure:
use AppExceptionsInvalidOrderException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (InvalidOrderException $e, $request) {
return response()->view('errors.invalid-order', [], 500);
});
}
You may also use the renderable
method to override the rendering behavior for built-in Laravel or Symfony exceptions such as NotFoundHttpException
. If the closure given to the renderable
method does not return a value, Laravel’s default exception rendering will be utilized:
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s register
method, you may define report
and render
methods directly on your custom exceptions. When these methods exist, they will be automatically called by the framework:
<?php
namespace AppExceptions;
use Exception;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(/* ... */);
}
}
If your exception extends an exception that is already renderable, such as a built-in Laravel or Symfony exception, you may return false
from the exception’s render
method to render the exception’s default HTTP response:
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
// Determine if the exception needs custom rendering...
return false;
}
If your exception contains custom reporting logic that is only necessary when certain conditions are met, you may need to instruct Laravel to sometimes report the exception using the default exception handling configuration. To accomplish this, you may return false
from the exception’s report
method:
/**
* Report the exception.
*
* @return bool|null
*/
public function report()
{
// Determine if the exception needs custom reporting...
return false;
}
Note
You may type-hint any required dependencies of thereport
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
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:
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
view template. This view will be rendered 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 SymfonyComponentHttpKernelExceptionHttpException
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 default 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
Fallback HTTP Error Pages
You may also define a «fallback» error page for a given series of HTTP status codes. This page will be rendered if there is not a corresponding page for the specific HTTP status code that occurred. To accomplish this, define a 4xx.blade.php
template and a 5xx.blade.php
template in your application’s resources/views/errors
directory.
Tutorial last revisioned on August 10, 2022 with Laravel 9
API-based projects are more and more popular, and they are pretty easy to create in Laravel. But one topic is less talked about — it’s error handling for various exceptions. API consumers often complain that they get «Server error» but no valuable messages. So, how to handle API errors gracefully? How to return them in «readable» form?
Main Goal: Status Code + Readable Message
For APIs, correct errors are even more important than for web-only browser projects. As people, we can understand the error from browser message and then decide what to do, but for APIs — they are usually consumed by other software and not by people, so returned result should be «readable by machines». And that means HTTP status codes.
Every request to the API returns some status code, for successful requests it’s usually 200, or 2xx with XX as other number.
If you return an error response, it should not contain 2xx code, here are most popular ones for errors:
Status Code | Meaning |
404 | Not Found (page or other resource doesn’t exist) |
401 | Not authorized (not logged in) |
403 | Logged in but access to requested area is forbidden |
400 | Bad request (something wrong with URL or parameters) |
422 | Unprocessable Entity (validation failed) |
500 | General server error |
Notice that if we don’t specify the status code for return, Laravel will do it automatically for us, and that may be incorrect. So it is advisable to specify codes whenever possible.
In addition to that, we need to take care of human-readable messages. So typical good response should contain HTTP error code and JSON result with something like this:
{
"error": "Resource not found"
}
Ideally, it should contain even more details, to help API consumer to deal with the error. Here’s an example of how Facebook API returns error:
{
"error": {
"message": "Error validating access token: Session has expired on Wednesday, 14-Feb-18 18:00:00 PST. The current time is Thursday, 15-Feb-18 13:46:35 PST.",
"type": "OAuthException",
"code": 190,
"error_subcode": 463,
"fbtrace_id": "H2il2t5bn4e"
}
}
Usually, «error» contents is what is shown back to the browser or mobile app. So that’s what will be read by humans, therefore we need to take care of that to be clear, and with as many details as needed.
Now, let’s get to real tips how to make API errors better.
Tip 1. Switch APP_DEBUG=false Even Locally
There’s one important setting in .env file of Laravel — it’s APP_DEBUG which can be false or true.
If you turn it on as true, then all your errors will be shown with all the details, including names of the classes, DB tables etc.
It is a huge security issue, so in production environment it’s strictly advised to set this to false.
But I would advise to turn it off for API projects even locally, here’s why.
By turning off actual errors, you will be forced to think like API consumer who would receive just «Server error» and no more information. In other words, you will be forced to think how to handle errors and provide useful messages from the API.
Tip 2. Unhandled Routes — Fallback Method
First situation — what if someone calls API route that doesn’t exist, it can be really possible if someone even made a typo in URL. By default, you get this response from API:
Request URL: http://q1.test/api/v1/offices
Request Method: GET
Status Code: 404 Not Found
{
"message": ""
}
And it is OK-ish message, at least 404 code is passed correctly. But you can do a better job and explain the error with some message.
To do that, you can specify Route::fallback() method at the end of routes/api.php, handling all the routes that weren’t matched.
Route::fallback(function(){
return response()->json([
'message' => 'Page Not Found. If error persists, contact info@website.com'], 404);
});
The result will be the same 404 response, but now with error message that give some more information about what to do with this error.
Tip 3. Override 404 ModelNotFoundException
One of the most often exceptions is that some model object is not found, usually thrown by Model::findOrFail($id). If we leave it at that, here’s the typical message your API will show:
{
"message": "No query results for model [AppOffice] 2",
"exception": "SymfonyComponentHttpKernelExceptionNotFoundHttpException",
...
}
It is correct, but not a very pretty message to show to the end user, right? Therefore my advice is to override the handling for that particular exception.
We can do that in app/Exceptions/Handler.php (remember that file, we will come back to it multiple times later), in render() method:
// Don't forget this in the beginning of file
use IlluminateDatabaseEloquentModelNotFoundException;
// ...
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Entry for '.str_replace('App', '', $exception->getModel()).' not found'], 404);
}
return parent::render($request, $exception);
}
We can catch any number of exceptions in this method. In this case, we’re returning the same 404 code but with a more readable message like this:
{
"error": "Entry for Office not found"
}
Notice: have you noticed an interesting method $exception->getModel()? There’s a lot of very useful information we can get from the $exception object, here’s a screenshot from PhpStorm auto-complete:
Tip 4. Catch As Much As Possible in Validation
In typical projects, developers don’t overthink validation rules, stick mostly with simple ones like «required», «date», «email» etc. But for APIs it’s actually the most typical cause of errors — that consumer posts invalid data, and then stuff breaks.
If we don’t put extra effort in catching bad data, then API will pass the back-end validation and throw just simple «Server error» without any details (which actually would mean DB query error).
Let’s look at this example — we have a store() method in Controller:
public function store(StoreOfficesRequest $request)
{
$office = Office::create($request->all());
return (new OfficeResource($office))
->response()
->setStatusCode(201);
}
Our FormRequest file app/Http/Requests/StoreOfficesRequest.php contains two rules:
public function rules()
{
return [
'city_id' => 'required|integer|exists:cities,id',
'address' => 'required'
];
}
If we miss both of those parameters and pass empty values there, API will return a pretty readable error with 422 status code (this code is produced by default by Laravel validation failure):
{
"message": "The given data was invalid.",
"errors": {
"city_id": ["The city id must be an integer.", "The city id field is required."],
"address": ["The address field is required."]
}
}
As you can see, it lists all fields errors, also mentioning all errors for each field, not just the first that was caught.
Now, if we don’t specify those validation rules and allow validation to pass, here’s the API return:
{
"message": "Server Error"
}
That’s it. Server error. No other useful information about what went wrong, what field is missing or incorrect. So API consumer will get lost and won’t know what to do.
So I will repeat my point here — please, try to catch as many possible situations as possible within validation rules. Check for field existence, its type, min-max values, duplication etc.
Tip 5. Generally Avoid Empty 500 Server Error with Try-Catch
Continuing on the example above, just empty errors are the worst thing when using API. But harsh reality is that anything can go wrong, especially in big projects, so we can’t fix or predict random bugs.
On the other hand, we can catch them! With try-catch PHP block, obviously.
Imagine this Controller code:
public function store(StoreOfficesRequest $request)
{
$admin = User::find($request->email);
$office = Office::create($request->all() + ['admin_id' => $admin->id]);
(new UserService())->assignAdminToOffice($office);
return (new OfficeResource($office))
->response()
->setStatusCode(201);
}
It’s a fictional example, but pretty realistic. Searching for a user with email, then creating a record, then doing something with that record. And on any step, something wrong may happen. Email may be empty, admin may be not found (or wrong admin found), service method may throw any other error or exception etc.
There are many way to handle it and to use try-catch, but one of the most popular is to just have one big try-catch, with catching various exceptions:
try {
$admin = User::find($request->email);
$office = Office::create($request->all() + ['admin_id' => $admin->id]);
(new UserService())->assignAdminToOffice($office);
} catch (ModelNotFoundException $ex) { // User not found
abort(422, 'Invalid email: administrator not found');
} catch (Exception $ex) { // Anything that went wrong
abort(500, 'Could not create office or assign it to administrator');
}
As you can see, we can call abort() at any time, and add an error message we want. If we do that in every controller (or majority of them), then our API will return same 500 as «Server error», but with much more actionable error messages.
Tip 6. Handle 3rd Party API Errors by Catching Their Exceptions
These days, web-project use a lot of external APIs, and they may also fail. If their API is good, then they will provide a proper exception and error mechanism (ironically, that’s kinda the point of this whole article), so let’s use it in our applications.
As an example, let’s try to make a Guzzle curl request to some URL and catch the exception.
Code is simple:
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
// ... Do something with that response
As you may have noticed, the Github URL is invalid and this repository doesn’t exist. And if we leave the code as it is, our API will throw.. guess what.. Yup, «500 Server error» with no other details. But we can catch the exception and provide more details to the consumer:
// at the top
use GuzzleHttpExceptionRequestException;
// ...
try {
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
} catch (RequestException $ex) {
abort(404, 'Github Repository not found');
}
Tip 6.1. Create Your Own Exceptions
We can even go one step further, and create our own exception, related specifically to some 3rd party API errors.
php artisan make:exception GithubAPIException
Then, our newly generated file app/Exceptions/GithubAPIException.php will look like this:
namespace AppExceptions;
use Exception;
class GithubAPIException extends Exception
{
public function render()
{
// ...
}
}
We can even leave it empty, but still throw it as exception. Even the exception name may help API user to avoid the errors in the future. So we do this:
try {
$client = new GuzzleHttpClient();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle123456');
} catch (RequestException $ex) {
throw new GithubAPIException('Github API failed in Offices Controller');
}
Not only that — we can move that error handling into app/Exceptions/Handler.php file (remember above?), like this:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error' => 'Entry for '.str_replace('App', '', $exception->getModel()).' not found'], 404);
} else if ($exception instanceof GithubAPIException) {
return response()->json(['error' => $exception->getMessage()], 500);
} else if ($exception instanceof RequestException) {
return response()->json(['error' => 'External API call failed.'], 500);
}
return parent::render($request, $exception);
}
Final Notes
So, here were my tips to handle API errors, but they are not strict rules. People work with errors in quite different ways, so you may find other suggestions or opinions, feel free to comment below and let’s discuss.
Finally, I want to encourage you to do two things, in addition to error handling:
- Provide detailed API documentation for your users, use packages like API Generator for it;
- While returning API errors, handle them in the background with some 3rd party service like Bugsnag / Sentry / Rollbar. They are not free, but they save massive amount of time while debugging. Our team uses Bugsnag, here’s a video example.