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.
Версия
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.
- 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.
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.
Custom 404, 500 error page in laravel 8. In this tutorial, we will show you how to create/build custom error pages in laravel 8 app. And you will learn step by step how to create custom 404, 500 error page in laravel apps.
Usually, laravel 8 display default error page 404, 500. But if you want to design of this pages. So, you can do it. This tutorial will guide you to step by step from scratch for how to create custom 404, 500 error pages in laravel
Sometimes, you need to create a blade files like 404.blade.php, 500.blade.php, etc on laravel apps. So navigate resources/views/errors) directory in laravel apps. And then create any custom error pages inside this folder.
Custom Error Pages in Laravel 8
- Create 404 View File
- Create 500 View File
- Modify Exceptions Handler
1: Create 404 View File
Go to resources/views folder and create a folder named errors.
Then inside this errors folder, create a file called 404.blade.php. So the location of our 404 page is resources/views/errors/404.blade.php
.
resources/views/errors/404.blade.php
<!DOCTYPE html> <html> <head> <title>Page Not Found</title> </head> <body> This is the custom 404 error page. </body> </html>
2: Create 500 View File
Go to resources/views folder and create a folder named errors.
Then inside this errors folder, create a file called 500.blade.php. So the location of our 500 page is resources/views/errors/500.blade.php
.
resources/views/errors/500.blade.php
<!DOCTYPE html> <html> <head> <title>Page Not Found</title> </head> <body> This is the custom 500 error page. </body> </html>
3: Modify Exceptions Handler
Now, navigate to app/Exceptions and open Handler.php
file and find the render() method. Then modify the render() method only as follow:
public function render($request, Exception $exception) { if ($this->isHttpException($exception)) { if ($exception->getStatusCode() == 404) { return response()->view('errors.' . '404', [], 404); } } return parent::render($request, $exception); }
as well as render 500 error page in this file as follow:
public function render($request, Exception $exception) { if ($this->isHttpException($exception)) { if ($exception->getStatusCode() == 404) { return response()->view('errors.' . '404', [], 404); } if ($exception->getStatusCode() == 500) { return response()->view('errors.' . '500', [], 500); } } return parent::render($request, $exception); }
Conclusion
Laravel 8 create custom error page example, you have learned how to create custom page for 404, 500 error in laravel apps. As well as how to use them.
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
Многих пользователей интересует вопрос о том, как создать кастомную 404 страницу в Laravel. В этой статье будет показано несколько примеров, по которым вы просто сможете добавить отображение кастомной страницы при возникших HTTP-ошибках.
-
- Настройка обработки исключений
- 1.1. Кастомная страница 404 ошибки
- 1.2. Кастомная страница для пользовательских исключений
-
- Настройка обработки исключений в Laravel 5.8
Исключения в PHP похожи на исключения в других языках программирования. Исключения генерируются при возникновении ошибки или неизвестного события. Все исключения PHP расширяют базовый класс исключений Exception
.
Помимо этой статьи, ранее была написана ещё одна, на тему обработки исключений при AJAX запросах, ошибках валидации и возвращению ошибок в формате JSON.
Laravel предоставляет класс app/Exceptions/Handler.php
, который проверяет все исключения, генерируемые в приложении. По сути, каждое исключение, генерируемое в приложении, может быть индивидуально настроено в этом файле, и может быть создан соответствующий ответ. То есть, вы можете создавать исключения не только на HTTP статус (404, 500, …), вы имеете возможность настроить рендеринг представления на исключение конкретного типа.
В этой статье я покажу, как создать кастомную страницу для ошибки 404. Вы увидите, как вернуть кастомную страницу в зависимости от типа исключения. По умолчанию Laravel возвращает такую 404 страницу.
Когда посетитель вашего сайта попадает на маршрут, которого не существует, то ваш сайт показывает ошибку 404. Это фактор также влияет и на SEO, где возвращение 404 страницы обязательно в случае, если данные не были найдены.
Итак, давайте посмотрим, как же можно кастомизировать страницу 404, как обрабатывать другие HTTP исключения и пользовательские исключениями в Laravel, и рендерить индивидуально настроенное представление.
Обработка исключений
Все изменения, связанные с обработкой исключений производятся в файле app / Exceptions / Handler.php
. В этом файле настраивается всё, что связанно с исключениями, потому, в этом файле и будут прописаны правила, которые будут возвращаться представления, в зависимости от кода HTTP-ошибки.
Кастомная 404 страница
Давайте создадим кастомную страницу 404 в Laravel. В файле app/Exceptions/Handler.php
нужно изменить метод render
:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
/** @var HttpExceptionInterface $exception */
if ($exception->getStatusCode() == 404) {
return response()->view('errors.404', [], 404);
}
}
return parent::render($request, $exception);
}
В методе render
мы проверяем, является ли исключение исключением типа HTTP. Это важно, потому что мы вызываем метод getStatusCode(), который доступен только для HTTP исключений. Если код ответа 404, то мы возвращаем соответствующее представление. Вы можете изменить название представления на какое-угодно, если пожелаете.
Но теперь нужно создать представление для страницы 404. Для этого, создайте новый файл представления: resources/views/404.blade.php
.
<!DOCTYPE html>
<html>
<head>
<title>Page not found - 404</title>
</head>
<body>
The page is new custom page.
</body>
</html>
Если же вы хотите создать кастомную страницу для любого другого исключения HTTP, просто добавьте новый оператор if и измените 404 с новым кодом состояния. Вот метод рендеринга для обработки пользовательских страниц кода состояния 404 и 500:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
/** @var HttpExceptionInterface $exception */
if ($exception->getStatusCode() == 404) {
return response()->view('errors.404', [], 404);
}
if ($exception->getStatusCode() == 500) {
return response()->view('errors.500', [], 500);
}
}
return parent::render($request, $exception);
}
Или же, чтобы этот метод не захламлялся большим количеством if-ов, можно просто описать конструкцию, в которой будет проверяться существование кастомного файла, и его подключение:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
/** @var HttpExceptionInterface $exception */
$view = "errors.{$exception->getStatusCode()}";
if(view()->exists($view)) {
return response()->view($view, [], $exception->getStatusCode());
}
}
return parent::render($request, $exception);
}
В результате чего, вам достаточно всего лишь добавить представление в папку resources/errors
с именем кода HTTP-ошибки (например, 404.blade.php
, 500.blade.php
и т.д.).
В результате чего, при обращении к несуществующей странице уже будет отрендерена новая кастомная страница.
Кастомная страница для пользовательского исключения
Для начала создадим кастомное исключение. Для этого, запустите следующий код, чтобы создать исключение с именем CustomTestingException.
php artisan make:exception CustomTestingException
И после чего, модифицируем метод уже знакомый метод render
в файле app/Exceptions/Handler.php
:
public function render($request, Exception $exception)
{
if ($exception instanceof CustomTestingException) {
return response()->view('errors.testing');
}
return parent::render($request, $exception);
}
Если исключение является экземпляром CustomTestingException
, оно вернет представление errors.testing
.
Вы также можете использовать функцию abort
с кодом 404, которая сгенерирует 404 HTTP-код ответа.
Кастомизая ошибок в Laravel 5.8
Если вы счастливый обладатель Laravel версии 5.8, то вам даже не потребуется модификация каких-либо файлов. Теперь вам достаточно всего лишь создать директорию errors
внутри resources/views
, и создать нужный файл, название которого должно совпадать с именем HTTP-кода ошибки: 404.blade.php, 500.blada.php, ...
По умолчанию Laravel отображает стандартный дизайн ошибок, однако, если вы создадите соответствующие файлы внутри директории errors, фреймворк возьмёт представления с неё.
Резюме
В этой статья я постарался подробно рассказать, как создать свою собственную кастомную страницу при ошибках в Laravel. На примере было рассмотрено несколько способов кастомизации страницы при 404 ошибке, 500, и других пользовательских кастомных ошибках.
Hey developers, today I’m going to show how to create custom error page in Laravel. We’re able to create custom error page for a specific error. In this article, I’ll create custom page for 404 error.
Table of Contents
- HTTP Status Codes
- Create 404 View File
- Modify Exceptions Handler
1. HTTP Status Codes
Here’s the list of HTTP status codes:
$http_status_codes = array(
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing', // WebDAV; RFC 2518
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information', // since HTTP/1.1
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status', // WebDAV; RFC 4918
208 => 'Already Reported', // WebDAV; RFC 5842
226 => 'IM Used', // RFC 3229
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other', // since HTTP/1.1
304 => 'Not Modified',
305 => 'Use Proxy', // since HTTP/1.1
306 => 'Switch Proxy',
307 => 'Temporary Redirect', // since HTTP/1.1
308 => 'Permanent Redirect', // approved as experimental RFC
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I'm a teapot', // RFC 2324
419 => 'Authentication Timeout', // not in RFC 2616
420 => 'Enhance Your Calm', // Twitter
420 => 'Method Failure', // Spring Framework
422 => 'Unprocessable Entity', // WebDAV; RFC 4918
423 => 'Locked', // WebDAV; RFC 4918
424 => 'Failed Dependency', // WebDAV; RFC 4918
424 => 'Method Failure', // WebDAV)
425 => 'Unordered Collection', // Internet draft
426 => 'Upgrade Required', // RFC 2817
428 => 'Precondition Required', // RFC 6585
429 => 'Too Many Requests', // RFC 6585
431 => 'Request Header Fields Too Large', // RFC 6585
444 => 'No Response', // Nginx
449 => 'Retry With', // Microsoft
450 => 'Blocked by Windows Parental Controls', // Microsoft
451 => 'Redirect', // Microsoft
451 => 'Unavailable For Legal Reasons', // Internet draft
494 => 'Request Header Too Large', // Nginx
495 => 'Cert Error', // Nginx
496 => 'No Cert', // Nginx
497 => 'HTTP to HTTPS', // Nginx
499 => 'Client Closed Request', // Nginx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates', // RFC 2295
507 => 'Insufficient Storage', // WebDAV; RFC 4918
508 => 'Loop Detected', // WebDAV; RFC 5842
509 => 'Bandwidth Limit Exceeded', // Apache bw/limited extension
510 => 'Not Extended', // RFC 2774
511 => 'Network Authentication Required', // RFC 6585
598 => 'Network read timeout error', // Unknown
599 => 'Network connect timeout error', // Unknown
);
The list is taken from Wikipedia.
2. Create 404 View File
Go to resources/views folder and create a folder named errors. In the errors folder, create a file called 404.blade.php. So the location of our 404 page is resources/views/errors/404.blade.php
.
In this file, you can set your custom design. I’m going to set a text only:
404.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
This is the custom 404 error page.
</body>
</html>
3. Modify Exceptions Handler
Open app/Exceptions/Handler.php
file and find the render() method. We’ll modify the render() function only. Here’s the modified code:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
return parent::render($request, $exception);
}
In this file, I’m checking status code 404 for the 404 error page. Like this, you can set condition for another error. Let’s see the code for 404 & 500 errors:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
if ($exception->getStatusCode() == 500) {
return response()->view('errors.' . '500', [], 500);
}
}
return parent::render($request, $exception);
}
We’ve created the custom page for 404 error & set condition in exceptions handler file. Now let’s see the output:
Through this Laravel tutorial, we would like to share with you how to easily create a custom error page 404 and 403, 500, 419, 255, 405 error pages in the Laravel application.
While working on a web application errors or more precisely exception can manifest at any time, Laravel framework handles exceptions beautifully.
It offers a handy error handler class which looks for almost every errors displayed in Laravel environment and returns an adequate response.
Generically, you can get the default error response if you configure debug property to false; nevertheless, you can create a custom error handling template.
Let’s handle custom errors in Laravel.
Create New Laravel Project
Start this tutorial by creating a brand new Laravel project using the following command:
composer create-project laravel/laravel --prefer-dist laravel-error-handling-example
You need to create blade views for error pages, move to this path resources/views/ inside here create errors folder and within the directory create 404.blade.php file. It will redirect you to the 404 page if you don’t find the associated URL.
Similarly you can create rest of the error handling blade views for 403, 500, 419, 255 and 405 exceptions:
Include the following code in resources/views/errors/404.blade.php error file.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>404 Custom Error Page Example</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5 pt-5">
<div class="alert alert-danger text-center">
<h2 class="display-3">404</h2>
<p class="display-5">Oops! Something is wrong.</p>
</div>
</div>
</body>
</html>
To test out the 404 custom error template, you need to start the application.
php artisan serve
As you know, 404 errors occur when you visit the non-existed link, so type the wrong URL in the browser’s address bar.
http://127.0.0.1:8000/not
Easy, isn’t it. This tutorial is over, i hope you liked it.
Содержание
- Error Handling
- Introduction
- Configuration
- The Exception Handler
- Reporting Exceptions
- Global Log Context
- Exception Log Context
- The report Helper
- Exception Log Levels
- Ignoring Exceptions By Type
- Rendering Exceptions
- Reportable & Renderable Exceptions
- HTTP Exceptions
- Custom HTTP Error Pages
- Fallback HTTP Error Pages
- Laravel Framework Russian Community
- Введение
- Конфигурирование
- Обработчик исключений
- Отчет об исключениях
- Глобальное содержимое журнала
- Контекст журнала исключений
- Помощник report
- Игнорирование исключений по типу
- Отображение исключений
- Отчетные и отображаемые исключения
- HTTP-исключения
- Пользовательские страницы ошибок HTTP
Error Handling
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
Note
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:
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:
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:
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 is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in most web projects.
Источник
Введение
Когда вы запускаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. Класс AppExceptionsHandler – это то место, где все исключения, созданные вашим приложением, регистрируются и затем отображаются пользователю. В этой документации мы углубимся в этот класс.
Конфигурирование
Параметр debug в конфигурационном файле config/app.php определяет, сколько информации об ошибке фактически отобразится пользователю. По умолчанию этот параметр установлен, чтобы учесть значение переменной окружения APP_DEBUG , которая содержится в вашем файле .env .
Во время локальной разработки вы должны установить для переменной окружения APP_DEBUG значение true . Во время эксплуатации приложения это значение всегда должно быть false . Если в рабочем окружении будет установлено значение true , вы рискуете раскрыть конфиденциальные значения конфигурации конечным пользователям вашего приложения.
Обработчик исключений
Отчет об исключениях
Все исключения обрабатываются классом AppExceptionsHandler . Этот класс содержит метод register , в котором вы можете зарегистрировать свои отчеты об исключениях и замыкания рендеринга. Мы подробно рассмотрим каждую из этих концепций. Отчеты об исключениях используются для регистрации исключений или отправки их во внешнюю службу, например Flare, Bugsnag или Sentry. По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией логирования. Однако вы можете регистрировать исключения как хотите.
Например, если вам нужно сообщать о различных типах исключений по-разному, вы можете использовать метод reportable для регистрации замыкания, которое должно быть выполнено, когда необходимо сообщить об исключении конкретного типа. Laravel определит о каком типе исключения сообщает замыкание с помощью типизации аргументов:
Когда вы регистрируете собственные замыкания для создания отчетов об исключениях, используя метод reportable , Laravel по-прежнему регистрирует исключение, используя конфигурацию логирования по умолчанию для приложения. Если вы хотите остановить распространение исключения в стек журналов по умолчанию, вы можете использовать метод stop при определении замыкания отчета или вернуть false из замыкания:
Чтобы настроить отчет об исключениях для переданного исключения, вы можете рассмотреть возможность использования отчетных исключений.
Глобальное содержимое журнала
Если доступно, Laravel автоматически добавляет идентификатор текущего пользователя в каждое сообщение журнала исключения в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context класса AppExceptionsHandler вашего приложения. Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:
Контекст журнала исключений
Хотя добавление контекста в каждое сообщение журнала может быть полезно, иногда конкретное исключение может иметь уникальный контекст, который вы хотели бы включить в свои журналы. Определив метод context для конкретного исключения вашего приложения, вы можете указать любые данные, относящиеся к этому исключению, которые должны быть добавлены в запись журнала исключения:
Помощник report
По желанию может потребоваться сообщить об исключении, но продолжить обработку текущего запроса. Помощник report позволяет вам быстро сообщить об исключении через обработчик исключений, не отображая страницу с ошибкой для пользователя:
Игнорирование исключений по типу
При создании приложения будут некоторые типы исключений, которые вы просто хотите игнорировать и никогда не сообщать о них. Обработчик исключений вашего приложения содержит свойство $dontReport , которое инициализируется пустым массивом. Ни о каких классах, добавленных в это свойство, никогда не будет сообщено; однако у них все еще может быть собственная логика отображения:
За кулисами Laravel уже игнорирует для вас некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 HTTP-ответ, сгенерированный при недопустимом CSRF-токене.
Отображение исключений
По умолчанию обработчик исключений Laravel будет преобразовывать исключения в HTTP-ответ за вас. Однако вы можете зарегистрировать свое замыкание для отображения исключений конкретного типа. Вы можете сделать это с помощью метода renderable обработчика исключений.
Замыкание, переданное методу renderable , должно вернуть экземпляр IlluminateHttpResponse , который может быть сгенерирован с помощью функции response . Laravel определит, какой тип исключения отображает замыкание с помощью типизации аргументов:
Вы также можете использовать метод renderable чтобы переопределить отображение для встроенных исключений Laravel или Symfony, таких, как NotFoundHttpException . Если замыкание, переданное методу renderable не возвращает значения, будет использоваться отрисовка исключений Laravel по умолчанию:
Отчетные и отображаемые исключения
Вместо проверки типов исключений в методе register обработчика исключений вы можете определить методы report и render непосредственно для ваших исключений. Если эти методы существуют, то они будут автоматически вызываться фреймворком:
Если ваше исключение расширяет исключение, которое уже доступно для визуализации, например встроенное исключение Laravel или Symfony, вы можете вернуть false из метода render исключения, чтобы отобразить HTTP-ответ исключения по умолчанию:
Если ваше исключение содержит пользовательскую логику отчетности, которая необходима только при выполнении определенных условий, то вам может потребоваться указать Laravel когда сообщать об исключении, используя конфигурацию обработки исключений по умолчанию. Для этого вы можете вернуть false из метода report исключения:
Вы можете указать любые требуемые зависимости метода report , и они будут автоматически внедрены в метод контейнером служб Laravel.
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок с сервера. Например, это может быть ошибка «страница не найдена» (404), «неавторизованный доступ» (401) или даже ошибка 500, сгенерированная разработчиком. Чтобы создать такой ответ из любой точки вашего приложения, вы можете использовать глобальный помощник abort :
Пользовательские страницы ошибок HTTP
Laravel позволяет легко отображать пользовательские страницы ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов HTTP-состояния 404, создайте файл resources/views/errors/404.blade.php . Это представление будет отображено для всех ошибок 404, сгенерированных вашим приложением. Шаблоны в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр SymfonyComponentHttpKernelExceptionHttpException , вызванный функцией abort , будет передан в шаблон как переменная $exception :
Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel с помощью команды vendor:publish Artisan. После публикации шаблонов вы можете настроить их по своему вкусу:
Источник
I want to show custom error page in my Laravel 5 app; for example any user type URL like http://www.example.com/url123
(wrong) but http://www.example.com/url
(right).
Default error show as :
Uh-oh, something went wrong! Error Code: 500
But instead I want to show my custom view
How I can achieve that as illustrated in the pages referenced below:
https://mattstauffer.co/blog/laravel-5.0-custom-error-pages#how-to
https://laracasts.com/discuss/channels/general-discussion/how-do-i-create-a-custom-404-error-page
My current app/Exceptions/Handler.php
:
<?php
namespace AppExceptions;
use Exception;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
use symfonyhttp-kernelSymfonyComponentHttpKernelExceptionNotFoundHttpException;
class Handler extends ExceptionHandler {
protected $dontReport = [
'SymfonyComponentHttpKernelExceptionHttpException'
];
public function report(Exception $e)
{
return parent::report($e);
}
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if($e instanceof NotFoundHttpException)
{
return response()->view('missing', [], 404);
}
else
{
return parent::render($request, $e);
}
}
}
And I’ve create a error view at resourcesviewserrors404.blade.php
but 404.blade.php
still does not get loaded.
nyedidikeke
6,5427 gold badges44 silver badges56 bronze badges
asked Feb 24, 2015 at 6:40
Kamlesh KumarKamlesh Kumar
1,5622 gold badges20 silver badges31 bronze badges
Im using Laravel 6.4 and for that, You can create custom error pages blade files and Laravel will do the rest for you. Run the following command in your project directory
php artisan vendor:publish --tag=laravel-errors
This will create blade files in resources/views/errors/.
eg for the 404 ERROR you will have it in resources/views/errors/404.blade.php.
.
Now Let’s say you wish to pass a Not Found Error in your sample code lets say a function to return a post category
/**
* Display the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function show($id)
{
$count = Post::find($id)->count();
if ($count < 1) return abort('404', 'The post you are looking for was not found');
}
The abort()
method will trigger a not found exception loading the blade file resources/views/errors/404.blade.php
and passing in the second parameter as the message. You can access this message in the blade file as
<h2>{{ $exception->getMessage() }}</h2>
Go to this link(official documentation) for details https://laravel.com/docs/6.x/errors#custom-http-error-pages
answered Jan 21, 2020 at 7:58
Thanks guys,
Now it is working successfully,
I just change my app/Exceptions/Handler.php :
<?php
namespace AppExceptions;
use Exception;
use IlluminateFoundationExceptionsHandler as ExceptionHandler;
class Handler extends ExceptionHandler {
protected $dontReport = [
'SymfonyComponentHttpKernelExceptionHttpException'
];
public function report(Exception $e)
{
return parent::report($e);
}
public function render($request, Exception $e)
{
if ($this->isHttpException($e)) {
return $this->renderHttpException($e);
} else {
return parent::render($request, $e);
}
}
}
and create a error view on : resourcesviewserrors404.blade.php
lin
17.7k4 gold badges56 silver badges82 bronze badges
answered Feb 24, 2015 at 10:22
Kamlesh KumarKamlesh Kumar
1,5622 gold badges20 silver badges31 bronze badges
2
first you need to type command
php artisan vendor:publish —tag=laravel-errors
It will create some error blade files in resources/views/errors such as 404,500,403,401,419,429,503. You can customize these pages as per your design requirement.
app/Exceptions/Handler.php
public function render($request, Throwable $exception)
{
$response = parent::render($request, $exception);
if ($response->status() === 500) {
return response(view('errors.500'), 500);
}
return $response;
}
app/config/app.php
‘debug’ => (bool) env(‘APP_DEBUG’, false)
Note: Do not create errors folder manually in view folder because some library files not creating in vendor folders. Its the reason to throw the error. please only do with the laravel command.
answered Sep 23, 2021 at 11:49
This worked for me in Laravel 5.5:-
/config/constants.php
define('ERROR_MSG_403', "You are not authorized to view that page!");
define('ERROR_MSG_404', "Page not found!");
define('ERROR_MSG_UNKNOWN', "Something went wrong!");
/app/Exceptions/Handler.php
public function render($request, Exception $e)
{
$response = [];
$response['exception'] = get_class($e);
$response['status_code'] = $e->getStatusCode();
switch($response['status_code'])
{
case 403:
$response['message'] = ERROR_MSG_403;
break;
case 404:
$response['message'] = ERROR_MSG_404;
break;
default:
$response['message'] = ERROR_MSG_UNKNOWN;
break;
}
return response()->view('Error.error', compact('response'));
// return parent::render($request, $exception);
}
/resources/views/Error/error.blade.php
<?=dd($response); //Implement your view layout here?>
answered Jul 20, 2018 at 10:06