Error exception laravel

Русская документация Laravel 8.x - Обработка ошибок (Exception)
  • Введение
  • Конфигурирование
  • Обработчик исключений

    • Отчет об исключениях
    • Игнорирование исключений по типу
    • Отображение исключений
    • Отчетные и отображаемые исключения
  • 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
    • 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.

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 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:

<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.

  1. 1. Введение
  2. 2. Настройка

    1. 2.1. Детализация ошибок
    2. 2.2. Хранилище журналов
    3. 2.3. Уровни важности событий
  3. 3. Обработчик исключений

    1. 3.1. Метод PHPreport()
    2. 3.2. Метод PHPrender()
  4. 4. HTTP-исключения

    1. 4.1. Свои страницы HTTP-ошибок
  5. 5. Журналы

Введение

Когда вы начинаете новый Laravel проект, обработка ошибок и исключений уже настроена для вас. Все происходящие в вашем приложении исключения записываются в журнал и отображаются пользователю в классе AppExceptionsHandler. В этой статье мы подробно рассмотрим этот класс.

Для журналирования Laravel использует библиотеку Monolog, которая обеспечивает поддержку различных мощных обработчиков журналов. В Laravel настроены несколько из них, благодаря чему вы можете выбрать между единым файлом журнала, ротируемыми файлами журналов и записью информации в системный журнал.

Настройка

Детализация ошибок

Параметр confdebug в файле настроек config/app.php определяет, сколько информации об ошибке показывать пользователю. По умолчанию этот параметр установлен в соответствии со значением переменной среды APP_DEBUG, которая хранится в файле .env.

Для локальной разработки вам следует установить переменную среды APP_DEBUG в значение true. В продакшн-среде эта переменная всегда должна иметь значение false. Если значение равно true на продакшн-сервере, вы рискуете раскрыть важные значения настроек вашим конечным пользователям.

Хранилище журналов

Изначально Laravel поддерживает запись журналов в единый файл (single), в отдельные файлы за каждый день (daily), в syslog и errorlog. Для использования определённого механизма хранения вам надо изменить параметр conflog в файле config/app.php. Например, если вы хотите использовать ежедневные файлы журнала вместо единого файла, вам надо установить значение log равное daily в файле настроек app:


+
5.3 5.2

добавлено в

5.3

(28.01.2017)

5.2

(08.12.2016)

Максимальное число ежедневных файлов журнала

При использовании режима daily Laravel по умолчанию хранит журналы только за последние 5 дней. Если вы хотите изменить число хранимых файлов, добавьте в файл app значение для параметра log_max_files:


+
5.3 5.2

добавлено в

5.3

(28.01.2017)

5.2

(08.12.2016)

Уровни важности событий

При использовании Monolog сообщения в журнале могут иметь разные уровни важности. По умолчанию Laravel сохраняет в журнал события всех уровней. Но на продакшн-сервере вы можете задать минимальный уровень важности, который необходимо заносить в журнал, добавив параметр conflog_level в файл app.php.

После задания этого параметра Laravel будет записывать события всех уровней начиная с указанного и выше. Например, при conflog_level равном error будут записываться события error, critical, alert и emergency:

conf'log_level' => env('APP_LOG_LEVEL', 'error'),

В Monolog используются следующие уровни важности — от меньшего к большему: debug, info, notice, warning, error, critical, alert, emergency.

Изменение настроек Monolog

Если вы хотите иметь полный контроль над конфигурацией Monolog для вашего приложения, вы можете использовать метод приложения PHPconfigureMonologUsing(). Вызов этого метода необходимо поместить в файл bootstrap/app.php прямо перед тем, как в нём возвращается переменная PHP$app:

PHP

$app->configureMonologUsing(function ($monolog) {
  
$monolog->pushHandler(...);
});

return 

$app;

Обработчик исключений

Метод PHPreport()

Все исключения обрабатываются классом AppExceptionsHandler. Этот класс содержит два метода: PHPreport() и PHPrender(). Рассмотрим каждый из них подробнее. Метод PHPreport() используется для занесения исключений в журнал или для отправки их во внешний сервис, такой как BugSnag или Sentry. По умолчанию метод PHPreport() просто передаёт исключение в базовую реализацию родительского класса, где это исключение зафиксировано. Но вы можете регистрировать исключения как пожелаете.

Например, если вам необходимо сообщать о различных типах исключений разными способами, вы можете использовать оператор сравнения PHP PHPinstanceof::

PHP

/**
 * Сообщить или зарегистрировать исключение.
 *
 * Это отличное место для отправки исключений в Sentry, Bugsnag, и т.д.
 *
 * @param  Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
  if (
$exception instanceof CustomException) {
    
//
  
}

  return 

parent::report($exception);
}

Игнорирование исключений заданного типа

Свойство обработчика исключений PHP$dontReport содержит массив с типами исключений, которые не будут заноситься в журнал. Например, исключения, возникающие при ошибке 404, а также при некоторых других типах ошибок, не записываются в журналы. При необходимости вы можете включить другие типы исключений в этот массив:

PHP

/**
 * Список типов исключений, о которых не надо сообщать.
 *
 * @var array
 */
protected $dontReport = [
  
IlluminateAuthAuthenticationException::class,
  
IlluminateAuthAccessAuthorizationException::class,
  
SymfonyComponentHttpKernelExceptionHttpException::class,
  
IlluminateDatabaseEloquentModelNotFoundException::class,
  
IlluminateValidationValidationException::class,
];

Метод PHPrender()

Метод PHPrender() отвечает за конвертацию исключения в HTTP-отклик, который должен быть возвращён браузеру. По умолчанию исключение передаётся в базовый класс, который генерирует для вас отклик. Но вы можете проверить тип исключения или вернуть ваш собственный отклик:

PHP

/**
 * Отрисовка HTTP-оклика для исключения.
 *
 * @param  IlluminateHttpRequest  $request
 * @param  Exception  $exception
 * @return IlluminateHttpResponse
 */
public function render($requestException $exception)
{
  if (
$exception instanceof CustomException) {
    return 
response()->view('errors.custom', [], 500);
  }

  return 

parent::render($request$exception);
}

HTTP-исключения

Некоторые исключения описывают коды HTTP-ошибок от сервера. Например, это может быть ошибка «страница не найдена» (404), «ошибка авторизации» (401) или даже сгенерированная разработчиком ошибка 500. Для возврата такого отклика из любого места в приложении можете использовать вспомогательный метод PHPabort():

Вспомогательный метод PHPabort() немедленно создаёт исключение, которое будет отрисовано обработчиком исключений. Или вы можете предоставить такой отклик:

PHP

abort(403'Unauthorized action.');

Свои страницы HTTP-ошибок

В Laravel можно легко возвращать свои собственные страницы для различных кодов HTTP-ошибок. Например, для выдачи собственной страницы для ошибки 404 создайте файл resources/views/errors/404.blade.php. Этот файл будет использован для всех ошибок 404, генерируемых вашим приложением. Представления в этой папке должны иметь имена, соответствующие кодам ошибок. Экземпляр HttpException, созданный функцией PHPabort(), будет передан в представление как переменная PHP$exception.

Журналы

Laravel обеспечивает простой простой уровень абстракции над мощной библиотекой Monolog. По умолчанию Laravel настроен на создание файла журнала в storage/logs. Вы можете записывать информацию в журнал при помощи фасада Log:

PHP

<?phpnamespace AppHttpControllers;

use 

IlluminateSupportFacadesLog;
//для версии 5.2 и ранее:
//use Log;
use AppUser;
use 
AppHttpControllersController;

class 

UserController extends Controller
{
  
/**
   * Показать профиль данного пользователя.
   *
   * @param  int  $id
   * @return Response
   */
  
public function showProfile($id)
  {
    
Log::info('Showing user profile for user: '.$id);

    return 

view('user.profile', ['user' => User::findOrFail($id)]);
  }
}

Регистратор событий предоставляет восемь уровней журналирования, описанных в RFC 5424: debug, info, notice, warning, error, critical, alert и emergency.

PHP

Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

Контекстная информация

Также в методы журналирования может быть передан массив контекстных данных:

PHP

Log::info('User failed to login.', ['id' => $user->id]);

Обращение к низкоуровневому экземпляру Monolog

В Monolog доступно множество дополнительных обработчиков для журналов. При необходимости вы можете получить доступ к низкоуровневому экземпляру Monolog, используемому в Laravel:

PHP

$monolog Log::getMonolog();


+
5.0

добавлено в

5.0

(08.02.2016)

Вы также можете зарегистрировать событие для перехвата всех сообщений, передаваемых в журнал.

Регистрация слушателя событий журнала

PHP

Log::listen(function($level$message$context)
{
  
//
});

Обычно веб-разработчики не следят за ошибками. Если что-то идет не так, то мы частенько видим дефолтный текст ошибки Laravel: «Whoops, something went wrong» или, что еще хуже, код исключения, который посетителю совсем ни к чему. Поэтому я решил написать пошаговую статью о том, как элегантно обрабатывать ошибки и показывать посетителю правильную информацию о произошедшем.

Примечание: в этой статье также будет показан пример создания собственной службы с внедрением зависимости и обработка исключений, создаваемых службой.

Подготовка: Задача поиска пользователя

Итак, у нас есть очень простой пример — форма для поиска пользователя по его идентификатору.

У нас есть два маршрута:

Route::get('/users', 'UserController@index')->name('users.index');
Route::post('/users/search', 'UserController@search')->name('users.search');

И контроллер с двумя методами:

class UserController extends Controller
{

    public function index()
    {
        return view('users.index');
    }

    public function search(Request $request)
    {
        $user = User::find($request->input('user_id'));
        return view('users.search', compact('user'));
    }

}

В файле resources/views/users/index.blade.php находится сама форма:

<form action="{{ route('users.search') }}" method="POST">
@csrf
<div class="form-group">
<input id="user_id" class="form-control" name="user_id" type="text" value="{{ old('user_id') }}" placeholder="User ID">
</div>
<input class="btn btn-info" type="submit" value="Search">
</form>

Если мы ищем существующего пользователя и он найден, мы видим такой результат:

Всё это находится в resources/views/users/search.blade.php:

<h3 class="page-title text-center">User found: {{ $user->name }}</h3>
<b>Email</b>: {{ $user->email }}
<br>
<b>Registered on</b>: {{ $user->created_at }}

Но это в идеальном случае, а что, если пользователь не найден?

Обработка исключений

Давайте вернемся в реальный мир. Мы не проверяем существование пользователя, в контроллере мы только делаем:

$user = User::find($request->input('user_id'));

И, если пользователь не найден, то получим это:

Или, понятное дело, мы можем задать APP_DEBUG=false в файле .env, и тогда браузер просто покажет пустую страницу с «Whoops, looks like something went wrong». Но для нашего посетителя все это совершенно бесполезно.

Еще одно быстрое исправление, которое мы можем сделать, это использовать User::findOrFail() вместо просто find() — тогда, если пользователь не найден, Laravel покажет страницу 404 с текстом «Sorry, the page you are looking for could not be found». Но это дефолтная страница ошибки для всего сайта. Для посетителя она, опять таки, бесполезна.

Поэтому нам нужно отлавливать ошибки, обрабатывать их и перенаправлять обратно в форму с действительно понятным сообщением об ошибке.

Нам нужно знать тип исключения и имя класса, которое оно будет возвращать. В случае с findOrFail() будет выдано Eloquent исключение ModelNotFoundException, поэтому нам нужно сделать так:

public function search(Request $request)
{
    try {
        $user = User::findOrFail($request->input('user_id'));
    } catch (ModelNotFoundException $exception) {
        return back()->withError($exception->getMessage())->withInput();
    }
    return view('users.search', compact('user'));
}

Теперь давайте покажем ошибку в Blade:

<h3 class="page-title text-center">Search for user by ID</h3>

@if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
@endif

<form action="{{ route('users.search') }}" method="POST">...</form>

Результат:

Отлично, мы отобразили ошибку! Но это еще не идеал, верно? Вместо $exception->getMessage() нам нужно показать наше собственное сообщение:

return back()->withError('User not found by ID ' . $request->input('user_id'))->withInput();

Финальный вариант!

Перемещаем обработку ошибок в Сервис

На данный момент мы взяли очень простой пример одного действия в контроллере — поиск пользователя. В реальном приложении все гораздо сложнее — обычно контроллер вызывает какой-нибудь внешний сервис или метод пакета, которые могут завершиться с какими-угодно ошибками.

Давайте создадим свой собственный сервис, который, по сути, делает то же самое, но будет генерировать исключение, поэтому контроллеру даже не потребуется знать текст сообщения.

Давайте переместим нашу логику в app/Services/UserService.php:

namespace AppServices;

use AppUser;
use IlluminateDatabaseEloquentModelNotFoundException;

class UserService
{

    public function search($user_id)
    {
        $user = User::find($user_id);
        if (!$user) {
            throw new ModelNotFoundException('User not found by ID ' . $user_id);
        }
        return $user;
    }

}

А в контроллере нам нужно вызвать этот сервис. Для начала мы внедрим его в метод __construct():

use AppServicesUserService;

class UserController extends Controller
{

    private $userService;

    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

// ...

Если вы не знакомы с внедрением зависимостей и как работает контейнер Laravel IOC, то вот официальная документация.

А вот так теперь выглядит наш метод search():

public function search(Request $request)
{
    try {
        $user = $this->userService->search($request->input('user_id'));
    } catch (ModelNotFoundException $exception) {
        return back()->withError($exception->getMessage())->withInput();
    }
    return view('users.search', compact('user'));
}

Обратите внимание, мы снова можем использовать $exception->getMessage(), вся проверка ошибок и логика сообщений происходит внутри службы. Мы удалили это из контроллера, он не должен заниматься этим.

Следующий Шаг: Создание собственного класса исключений

Последняя глава этой статьи посвящена улучшению архитектуры. Это когда ваш сервис генерирует свое собственное исключение, связанное с этой конкретной ошибкой, и, в зависимости от ошибки, может быть несколько классов исключений. Хорошим примером такой архитектуры является библиотека Stripe, ее использование выглядит так:

try {
  // Use Stripe's library to make requests...
} catch(StripeErrorCard $e) {
  // Since it's a decline, StripeErrorCard will be caught
  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "n");
  print('Type is:' . $err['type'] . "n");
  print('Code is:' . $err['code'] . "n");
  // param is '' in this case
  print('Param is:' . $err['param'] . "n");
  print('Message is:' . $err['message'] . "n");
} catch (StripeErrorRateLimit $e) {
  // Too many requests made to the API too quickly
} catch (StripeErrorInvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (StripeErrorAuthentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (StripeErrorApiConnection $e) {
  // Network communication with Stripe failed
} catch (StripeErrorBase $e) {
  // Display a very generic error to the user, and maybe send
  // yourself an email
} catch (Exception $e) {
  // Something else happened, completely unrelated to Stripe
}

Итак, как мы можем создать наш собственный класс исключений? Очень просто — с помощью команды Artisan:

php artisan make:exception UserNotFoundException

Сгенерируется app/Exceptions/UserNotFoundException.php:

namespace AppExceptions;

use Exception;

class UserNotFoundException extends Exception
{
    //
}

Здесь же ничего нет, верно? Давайте заполним наше исключение логикой.
В этом классе может быть два метода:

  • report() — используется, если вы хотите сделать дополнительную запись в журнал — отправить сообщение об ошибке в BugSnag, на почту, в Slack и т. д.
  • render() — используется, если вы хотите сделать редирект с ошибкой или вернуть HTTP-ответ (например, свой собственный файл Blade ) непосредственно из класса Exception

Итак, для этого примера мы cделаем метод report():

namespace AppExceptions;

use Exception;

class UserNotFoundException extends Exception
{
    /**
     * Report or log an exception.
     *
     * @return void
     */
    public function report()
    {
        Log::debug('User not found');
    }
}

А вот так мы вызываем это исключение из контроллера:

public function search(Request $request)
{
    try {
        $user = $this->userService->search($request->input('user_id'));
    } catch (UserNotFoundException $exception) {
        report($exception);
        return back()->withError($exception->getMessage())->withInput();
    }
    return view('users.search', compact('user'));
}

Итак, это всё, что я хотел рассказать вам об обработке исключений и использовании Сервисов.

Я понимаю, что мой пример очень упрощен, и другие люди могут использовать исключения иными способами, но я надеюсь, что в этой статье дан основой обзор исключений и причин, по которым вы должны их использовать.

Подробнее об исключениях и обработке ошибок: официальная документация Laravel.

Автор: Povilas Korop
Перевод: Алексей Широков

Задать вопросы по урокам можно на нашем форуме.

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.

Anyone know what is the best way to handle errors in Laravel, there is any rules or something to follow ?

Currently i’m doing this :

public function store(Request $request)
{
  $plate = Plate::create($request->all());

  if ($plate) {
    return $this->response($this->plateTransformer->transform($plate));
  } else {
    // Error handling ?
    // Error 400 bad request
    $this->setStatusCode(400);
    return $this->responseWithError("Store failed.");
  }
}

And the setStatusCode and responseWithError come from the father of my controller :

public function setStatusCode($statusCode)
{
    $this->statusCode = $statusCode;

    return $this;
}

public function responseWithError ($message )
{
    return $this->response([
        'error' => [
            'message' => $message,
            'status_code' => $this->getStatusCode()
        ]
    ]);

}

But is this a good way to handle the API errors, i see some different way to handle errors on the web, what is the best ?

Thanks.

asked Jun 27, 2018 at 14:17

Spialdor's user avatar

1

Try this, i have used it in my project (app/Exceptions/Handler.php)

public function render($request, Exception $exception)
{
    if ($request->wantsJson()) {   //add Accept: application/json in request
        return $this->handleApiException($request, $exception);
    } else {
        $retval = parent::render($request, $exception);
    }

    return $retval;
}

Now Handle Api exception

private function handleApiException($request, Exception $exception)
{
    $exception = $this->prepareException($exception);

    if ($exception instanceof IlluminateHttpExceptionHttpResponseException) {
        $exception = $exception->getResponse();
    }

    if ($exception instanceof IlluminateAuthAuthenticationException) {
        $exception = $this->unauthenticated($request, $exception);
    }

    if ($exception instanceof IlluminateValidationValidationException) {
        $exception = $this->convertValidationExceptionToResponse($exception, $request);
    }

    return $this->customApiResponse($exception);
}

After that custom Api handler response

private function customApiResponse($exception)
{
    if (method_exists($exception, 'getStatusCode')) {
        $statusCode = $exception->getStatusCode();
    } else {
        $statusCode = 500;
    }

    $response = [];

    switch ($statusCode) {
        case 401:
            $response['message'] = 'Unauthorized';
            break;
        case 403:
            $response['message'] = 'Forbidden';
            break;
        case 404:
            $response['message'] = 'Not Found';
            break;
        case 405:
            $response['message'] = 'Method Not Allowed';
            break;
        case 422:
            $response['message'] = $exception->original['message'];
            $response['errors'] = $exception->original['errors'];
            break;
        default:
            $response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $exception->getMessage();
            break;
    }

    if (config('app.debug')) {
        $response['trace'] = $exception->getTrace();
        $response['code'] = $exception->getCode();
    }

    $response['status'] = $statusCode;

    return response()->json($response, $statusCode);
}

Always add Accept: application/json in your api or json request.

answered Jun 27, 2018 at 14:38

rkj's user avatar

rkjrkj

7,8692 gold badges26 silver badges32 bronze badges

5

Laravel is already able to manage json responses by default.

Withouth customizing the render method in appHandler.php you can simply throw a SymfonyComponentHttpKernelExceptionHttpException, the default handler will recognize if the request header contains Accept: application/json and will print a json error message accordingly.

If debug mode is enabled it will output the stacktrace in json format too.

Here is a quick example:

<?php

...

use SymfonyComponentHttpKernelExceptionHttpException;

class ApiController
{
    public function myAction(Request $request)
    {
        try {
            // My code...
        } catch (Exception $e) {
            throw new HttpException(500, $e->getMessage());
        }

        return $myObject;
    }
}

Here is laravel response with debug off

{
    "message": "My custom error"
}

And here is the response with debug on

{
    "message": "My custom error",
    "exception": "Symfony\Component\HttpKernel\Exception\HttpException",
    "file": "D:\www\myproject\app\Http\Controllers\ApiController.php",
    "line": 24,
    "trace": [
        {
            "file": "D:\www\myproject\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php",
            "line": 48,
            "function": "myAction",
            "class": "App\Http\Controllers\ApiController",
            "type": "->"
        },
        {
            "file": "D:\www\myproject\vendor\laravel\framework\src\Illuminate\Routing\Route.php",
            "line": 212,
            "function": "dispatch",
            "class": "Illuminate\Routing\ControllerDispatcher",
            "type": "->"
        },

        ...
    ]
}

Using HttpException the call will return the http status code of your choice (in this case internal server error 500)

answered Dec 14, 2018 at 20:08

Andrea Mauro's user avatar

Andrea MauroAndrea Mauro

7431 gold badge8 silver badges14 bronze badges

4

In my opinion I’d keep it simple.

Return a response with the HTTP error code and a custom message.

return response()->json(['error' => 'You need to add a card first'], 500);

Or if you want to throw a caught error you could do :

   try {
     // some code
    } catch (Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    }

You can even use this for sending successful responses:

return response()->json(['activeSubscription' => $this->getActiveSubscription()], 200);

This way no matter which service consumes your API it can expect to receive the same responses for the same requests.

You can also see how flexible you can make it by passing in the HTTP status code.

answered Jun 28, 2018 at 15:59

user3574492's user avatar

user3574492user3574492

6,0359 gold badges49 silver badges103 bronze badges

If you are using Laravel 8+, you can do it simply by adding these lines in Exception/Handler.php on register() method

    $this->renderable(function (NotFoundHttpException $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Record not found.'
            ], 404);
        }
    });

answered Jun 14, 2022 at 22:42

Oussama's user avatar

For me, the best way is to use specific Exception for API response.

If you use Laravel version > 5.5, you can create your own exception with report() and render() methods. Use command:
php artisan make:exception AjaxResponseException

It will create AjaxResponseException.php at: app/Exceptions/
After that fill it with your logic. For example:

/**
 * Report the exception.
 *
 * @return void
 */
public function report()
{
    Debugbar::log($this->message);
}

/**
 * Render the exception into an HTTP response.
 *
 * @param  IlluminateHttpRequest  $request
 * @return JsonResponse|Response
 */
public function render($request)
{
    return response()->json(['error' => $this->message], $this->code);
}

Now, you can use it in your ...Controller with try/catch functionality.
For example in your way:

public function store(Request $request)
{
    try{
        $plate = Plate::create($request->all());

        if ($plate) {
            return $this->response($this->plateTransformer->transform($plate));
        }

        throw new AjaxResponseException("Plate wasn't created!", 404);

    }catch (AjaxResponseException $e) {
        throw new AjaxResponseException($e->getMessage(), $e->getCode());
    }
}

That’s enough to make your code more easier for reading, pretty and useful.
Best regards!

answered Apr 12, 2021 at 15:28

Max Lyu's user avatar

For Laravel 8+ in file AppExceptionsHander.php inside method register() paste this code:

$this->renderable(function (Throwable $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => $e->getMessage(),
                'code' => $e->getCode(),
            ], 404);
        }
    });

answered Jun 6, 2022 at 17:36

Jean Freitas's user avatar

I think it would be better to modify existing behaviour implemented in app/Exceptions/Handler.php than overriding it.

You can modify JSONResponse returned by parent::render($request, $exception); and add/remove data.

Example implementation:
app/Exceptions/Handler.php

use IlluminateSupportArr;

// ... existing code

public function render($request, Exception $exception)
{
    if ($request->is('api/*')) {
        $jsonResponse = parent::render($request, $exception);
        return $this->processApiException($jsonResponse);
    }

    return parent::render($request, $exception);
}

protected function processApiException($originalResponse)
{
    if($originalResponse instanceof JsonResponse){
        $data = $originalResponse->getData(true);
        $data['status'] = $originalResponse->getStatusCode();
        $data['errors'] = [Arr::get($data, 'exception', 'Something went wrong!')];
        $data['message'] = Arr::get($data, 'message', '');
        $originalResponse->setData($data);
    }

    return $originalResponse;
}

answered Feb 26, 2020 at 9:12

Андрей Русев's user avatar

Андрей РусевАндрей Русев

1871 gold badge1 silver badge13 bronze badges

Well, all answers are ok right now, but also they are using old ways.
After Laravel 8, you can simply change your response in register() method by introducing your exception class as renderable:

<?php


namespace YourNamespace;


use IlluminateFoundationExceptionsHandler as ExceptionHandler;


class Handler extends ExceptionHandler
{
    /**
     * 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);
            }
        });
    }
}

answered Dec 12, 2021 at 9:06

mohammad hosein abedini's user avatar

Using some code from @RKJ best answer I have handled the errors in this way:

Open «IlluminateFoundationExceptionsHandler» class and search for a method named «convertExceptionToArray». This method converts the HTTP exception into an array to be shown as a response. In this method, I have just tweaked a small piece of code that will not affect loose coupling.

So replace convertExceptionToArray method with this one

protected function convertExceptionToArray(Exception $e, $response=false)
    {

        return config('app.debug') ? [
            'message' => $e->getMessage(),
            'exception' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => collect($e->getTrace())->map(function ($trace) {
                return Arr::except($trace, ['args']);
            })->all(),
        ] : [
            'message' => $this->isHttpException($e) ? ($response ? $response['message']: $e->getMessage()) : 'Server Error',
        ];
    }

Now navigate to the AppExceptionsHandler class and paste the below code just above the render method:

public function convertExceptionToArray(Exception $e, $response=false){

        if(!config('app.debug')){
            $statusCode=$e->getStatusCode();
            switch ($statusCode) {
            case 401:
                $response['message'] = 'Unauthorized';
                break;
            case 403:
                $response['message'] = 'Forbidden';
                break;
            case 404:
                $response['message'] = 'Resource Not Found';
                break;
            case 405:
                $response['message'] = 'Method Not Allowed';
                break;
            case 422:
                $response['message'] = 'Request unable to be processed';
                break;
            default:
                $response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $e->getMessage();
                break;
            }
        }

        return parent::convertExceptionToArray($e,$response);
    }

Basically, we overrided convertExceptionToArray method, prepared the response message, and called the parent method by passing the response as an argument.

Note: This solution will not work for Authentication/Validation errors but most of the time these both errors are well managed by Laravel with proper human-readable response messages.

answered Oct 7, 2020 at 22:02

Hasnain Abid Khanzada's user avatar

1

In your handler.php This should work for handling 404 Exception.

public function render($request, Throwable $exception ){
    if ($exception instanceof ModelNotFoundException) {
        return response()->json([
            'error' => 'Data not found'
        ], 404);
    }
    return parent::render($request, $exception);
}

answered Dec 9, 2020 at 11:32

Muhammad's user avatar

MuhammadMuhammad

3093 silver badges19 bronze badges

0

You don’t have to do anything special. IlluminateFoundationExceptionsHandler handles everything for you. When you pass Accept: Application/json header it will return json error response. if debug mode is on you will get exception class, line number, file, trace if debug is off you will get the error message. You can override convertExceptionToArray. Look at the default implementation.

    return config('app.debug') ? [
        'message' => $e->getMessage(),
        'exception' => get_class($e),
        'file' => $e->getFile(),
        'line' => $e->getLine(),
        'trace' => collect($e->getTrace())->map(function ($trace) {
            return Arr::except($trace, ['args']);
        })->all(),
    ] : [
        'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
    ];

answered Nov 28, 2022 at 2:04

Sahib Khan's user avatar

Sahib KhanSahib Khan

5374 silver badges18 bronze badges

As @shahib-khan said,

this happens in debug mode and is handled by Laravel in production mode.
you can see base method code in
IlluminateFoundationExceptionsHandler::convertExceptionToArray

  protected function convertExceptionToArray(Throwable $e)
    {
        return config('app.debug') ? [
            'message' => $e->getMessage(),
            'exception' => get_class($e),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => collect($e->getTrace())->map(fn ($trace) => Arr::except($trace, ['args']))->all(),
        ] : [
            'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
        ];
    }

Therefore, I overrode the the convertExceptionToArray function in app/Exceptions/Handler

of course, still in debug mode, if the exception is thrown, you can track it in the Laravel.log.

 protected function convertExceptionToArray(Throwable $e)
    {
        return  [
            'message' => $this->isHttpException($e) ? $e->getMessage() : 'Server Error',
        ];
    }

answered Dec 29, 2022 at 11:01

fatemeh sadeghi's user avatar

Add header to your API endpoint. which works for me. it will handle the error request properly.

Accept: application/json

answered Jan 24 at 4:57

Najathi's user avatar

NajathiNajathi

2,20123 silver badges23 bronze badges

Понравилась статья? Поделить с друзьями:
  • Error exception in steamclient dll at offset 0x01d00000
  • Error eperm operation not permitted open discord
  • Error exception in asgi application fastapi
  • Error exception handling disabled use fexceptions to enable
  • Error exception handling console input java io ioexception неверный дескриптор