Laravel коды ошибок

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 App\Exceptions\Handler 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 App\Exceptions\Handler 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.

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 determine what type of exception the closure reports by examining the type-hint of the closure:

use App\Exceptions\InvalidOrderException;

/**

* Register the exception handling callbacks for the application.

*/

public function register(): void

{

$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 defining a context method on your application’s App\Exceptions\Handler 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<string, mixed>

*/

protected function context(): array

{

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 exceptions, you may specify any data relevant to that exception that should be added to the exception’s log entry:

<?php

namespace App\Exceptions;

use Exception;

class InvalidOrderException extends Exception

{

// ...

/**

* Get the exception's context information.

*

* @return array<string, mixed>

*/

public function context(): array

{

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(string $value): bool

{

try {

// Validate the value...

} catch (Throwable $e) {

report($e);

return false;

}

}

Deduplicating Reported Exceptions

If you are using the report function throughout your application, you may occasionally report the same exception multiple times, creating duplicate entries in your logs.

If you would like to ensure that a single instance of an exception is only ever reported once, you may call the exception handler’s dontReportDuplicates method. Typically, this method should be invoked from the boot method of your application’s AppServiceProvider:

use Illuminate\Contracts\Debug\ExceptionHandler;

/**

* Bootstrap any application services.

*/

public function boot(ExceptionHandler $exceptionHandler): void

{

$exceptionHandler->dontReportDuplicates();

}

Now, when the report helper is called with the same instance of an exception, only the first call will be reported:

$original = new RuntimeException('Whoops!');

report($original); // reported

try {

throw $original;

} catch (Throwable $caught) {

report($caught); // ignored

}

report($original); // ignored

report($caught); // ignored

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 a $levels property on your application’s exception handler. This property should contain an array of exception types and their associated log levels:

use PDOException;

use Psr\Log\LogLevel;

/**

* A list of exception types with their corresponding custom log levels.

*

* @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>

*/

protected $levels = [

PDOException::class => LogLevel::CRITICAL,

];

Ignoring Exceptions By Type

When building your application, there will be some types of exceptions you never want to report. To ignore these exceptions, define a $dontReport property on your application’s exception handler. Any classes that you add to this property will never be reported; however, they may still have custom rendering logic:

use App\Exceptions\InvalidOrderException;

/**

* A list of the exception types that are not reported.

*

* @var array<int, class-string<\Throwable>>

*/

protected $dontReport = [

InvalidOrderException::class,

];

Internally, Laravel already ignores some types of errors for you, such as exceptions resulting from 404 HTTP errors or 419 HTTP responses generated by invalid CSRF tokens. If you would like to instruct Laravel to stop ignoring a given type of exception, you may invoke the stopIgnoring method within your exception handler’s register method:

use Symfony\Component\HttpKernel\Exception\HttpException;

/**

* Register the exception handling callbacks for the application.

*/

public function register(): void

{

$this->stopIgnoring(HttpException::class);

// ...

}

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 by invoking the renderable method within your exception handler.

The closure passed to the renderable method should return an instance of Illuminate\Http\Response, which may be generated via the response helper. Laravel will determine what type of exception the closure renders by examining the type-hint of the closure:

use App\Exceptions\InvalidOrderException;

use Illuminate\Http\Request;

/**

* Register the exception handling callbacks for the application.

*/

public function register(): void

{

$this->renderable(function (InvalidOrderException $e, Request $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 Illuminate\Http\Request;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**

* Register the exception handling callbacks for the application.

*/

public function register(): void

{

$this->renderable(function (NotFoundHttpException $e, Request $request) {

if ($request->is('api/*')) {

return response()->json([

'message' => 'Record not found.'

], 404);

}

});

}

Reportable & Renderable Exceptions

Instead of defining custom reporting and rendering behavior in your exception handler’s register method, you may define report and render methods directly on your application’s exceptions. When these methods exist, they will automatically be called by the framework:

<?php

namespace App\Exceptions;

use Exception;

use Illuminate\Http\Request;

use Illuminate\Http\Response;

class InvalidOrderException extends Exception

{

/**

* Report the exception.

*/

public function report(): void

{

// ...

}

/**

* Render the exception into an HTTP response.

*/

public function render(Request $request): Response

{

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.

*/

public function render(Request $request): Response|bool

{

if (/** Determine if the exception needs custom rendering */) {

return response(/* ... */);

}

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.

*/

public function report(): bool

{

if (/** Determine if the exception needs custom reporting */) {

// ...

return true;

}

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:

abort(404);

Custom HTTP Error Pages

Laravel makes it easy to display custom error pages for various HTTP status codes. For example, 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 for 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 Symfony\Component\HttpKernel\Exception\HttpException instance raised by the abort function will be passed to the view as an $exception variable:

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

You may publish Laravel’s 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.

  • Введение
  • Конфигурирование
  • Обработчик исключений

    • Отчет об исключениях
    • Игнорирование исключений по типу
    • Отображение исключений
    • Отчетные и отображаемые исключения
    • Сопоставление исключений по типу
  • HTTP-исключения

    • Пользовательские страницы ошибок HTTP

Введение

Когда вы запускаете новый проект Laravel, обработка ошибок и исключений уже настроена для вас. Класс App\Exceptions\Handler – это то место, где все исключения, созданные вашим приложением, регистрируются и затем отображаются пользователю. В этой документации мы углубимся в этот класс.

Конфигурирование

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

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

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

Отчет об исключениях

Все исключения обрабатываются классом App\Exceptions\Handler. Этот класс содержит метод register, в котором вы можете зарегистрировать свои отчеты об исключениях и замыкания рендеринга. Мы подробно рассмотрим каждую из этих концепций. Отчеты об исключениях используются для регистрации исключений или отправки их во внешнюю службу, например Flare, Bugsnag или Sentry. По умолчанию исключения будут регистрироваться в соответствии с вашей конфигурацией логирования. Однако вы можете регистрировать исключения как хотите.

Например, если вам нужно сообщать о различных типах исключений по-разному, вы можете использовать метод reportable для регистрации замыкания, которое должно быть выполнено, когда необходимо сообщить об исключении конкретного типа. Laravel определит о каком типе исключения сообщает замыкание с помощью типизации аргументов:

use App\Exceptions\InvalidOrderException;

/**
 * Зарегистрировать замыкания, обрабатывающие исключения приложения.
 *
 * @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 класса App\Exceptions\Handler вашего приложения. Эта информация будет включена в каждое сообщение журнала исключения, написанное вашим приложением:

/**
 * Получить переменные контекста по умолчанию для ведения журнала.
 *
 * @return array
 */
protected function context()
{
    return array_merge(parent::context(), [
        'foo' => 'bar',
    ]);
}

Контекст журнала исключений

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

<?php

namespace App\Exceptions;

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 App\Exceptions\InvalidOrderException;

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

За кулисами Laravel уже игнорирует для вас некоторые типы ошибок, такие как исключения, возникающие из-за ошибок 404 HTTP «не найдено» или 419 HTTP-ответ, сгенерированный при недопустимом CSRF-токене.

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

По умолчанию обработчик исключений Laravel будет преобразовывать исключения в HTTP-ответ за вас. Однако вы можете зарегистрировать свое замыкание для отображения исключений конкретного типа. Вы можете сделать это с помощью метода renderable обработчика исключений.

Замыкание, переданное методу renderable, должно вернуть экземпляр Illuminate\Http\Response, который может быть сгенерирован с помощью функции response. Laravel определит, какой тип исключения отображает замыкание с помощью типизации аргументов:

use App\Exceptions\InvalidOrderException;

/**
 * Зарегистрировать замыкания, обрабатывающие исключения приложения.
 *
 * @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 Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Зарегистрировать замыкания, обрабатывающие исключения приложения.
 *
 * @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 App\Exceptions;

use Exception;

class InvalidOrderException extends Exception
{
    /**
     * Отчитаться об исключении.
     *
     * @return bool|null
     */
    public function report()
    {
        //
    }

    /**
     * Преобразовать исключение в HTTP-ответ.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function render($request)
    {
        return response(...);
    }
}

Если ваше исключение расширяет исключение, которое уже доступно для визуализации, например встроенное исключение Laravel или Symfony, вы можете вернуть false из метода render исключения, чтобы отобразить HTTP-ответ исключения по умолчанию:

/**
 * Преобразовать исключение в HTTP-ответ.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function render($request)
{
    // Определить, требуется ли для исключения пользовательское отображение...

    return false;
}

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

/**
 * Сообщить об исключении.
 *
 * @return bool|null
 */
public function report()
{
    // Определить, требуется ли для исключения пользовательская отчетность ...

    return false;
}

Вы можете указать любые требуемые зависимости метода report, и они будут автоматически внедрены в метод контейнером служб Laravel.

Сопоставление исключений по типу

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

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

use League\Flysystem\Exception;
use App\Exceptions\FilesystemException;

/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
 */
public function register()
{
    $this->map(Exception::class, FilesystemException::class);
}

Если вы хотите больше контролировать создание целевого исключения, вы можете передать методу map замыкание:

use League\Flysystem\Exception;
use App\Exceptions\FilesystemException;

$this->map(fn (Exception $e) => new FilesystemException($e));

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

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

abort(404);

Пользовательские страницы ошибок HTTP

Laravel позволяет легко отображать пользовательские страницы ошибок для различных кодов состояния HTTP. Например, если вы хотите настроить страницу ошибок для кодов HTTP-состояния 404, создайте файл resources/views/errors/404.blade.php. Это представление будет отображено для всех ошибок 404, сгенерированных вашим приложением. Шаблоны в этом каталоге должны быть названы в соответствии с кодом состояния HTTP, которому они соответствуют. Экземпляр Symfony\Component\HttpKernel\Exception\HttpException, вызванный функцией abort, будет передан в шаблон как переменная $exception:

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

Вы можете опубликовать стандартные шаблоны страниц ошибок Laravel с помощью команды vendor:publish Artisan. После публикации шаблонов вы можете настроить их по своему вкусу:

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

Errors & Logging

  • Introduction
  • Configuration
    • Error Detail
    • Log Storage
    • Log Severity Levels
    • Custom Monolog Configuration
  • The Exception Handler
    • Report Method
    • Render Method
  • HTTP Exceptions
    • Custom HTTP Error Pages
  • Logging

Introduction

When you start a new Laravel project, error and exception handling is already configured for you. The App\Exceptions\Handler class is where all exceptions triggered by your application are logged and then rendered back to the user. We’ll dive deeper into this class throughout this documentation.

For logging, Laravel utilizes the Monolog library, which provides support for a variety of powerful log handlers. Laravel configures several of these handlers for you, allowing you to choose between a single log file, rotating log files, or writing error information to the system log.

Configuration

Error Detail

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.

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

Log Storage

Out of the box, Laravel supports writing log information to single files, daily files, the syslog, and the errorlog. To configure which storage mechanism Laravel uses, you should modify the log option in your config/app.php configuration file. For example, if you wish to use daily log files instead of a single file, you should set the log value in your app configuration file to daily:

'log' => 'daily'

Maximum Daily Log Files

When using the daily log mode, Laravel will only retain five days of log files by default. If you want to adjust the number of retained files, you may add a log_max_files configuration value to your app configuration file:

'log_max_files' => 30

Log Severity Levels

When using Monolog, log messages may have different levels of severity. By default, Laravel writes all log levels to storage. However, in your production environment, you may wish to configure the minimum severity that should be logged by adding the log_level option to your app.php configuration file.

Once this option has been configured, Laravel will log all levels greater than or equal to the specified severity. For example, a default log_level of error will log error, critical, alert, and emergency messages:

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

{tip} Monolog recognizes the following severity levels — from least severe to most severe: debug, info, notice, warning, error, critical, alert, emergency.

Custom Monolog Configuration

If you would like to have complete control over how Monolog is configured for your application, you may use the application’s configureMonologUsing method. You should place a call to this method in your bootstrap/app.php file right before the $app variable is returned by the file:

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

return $app;

The Exception Handler

The Report Method

All exceptions are handled by the App\Exceptions\Handler class. This class contains two methods: report and render. We’ll examine each of these methods in detail. The report method is used to log exceptions or send them to an external service like Bugsnag or Sentry. By default, the report method simply passes the exception to the base class where the exception is logged. However, 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 PHP instanceof comparison operator:

/**
 * Report or log an exception.
 *
 * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
 *
 * @param  \Exception  $exception
 * @return void
 */
public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        //
    }

    return parent::report($exception);
}

Ignoring Exceptions By Type

The $dontReport property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:

/**
 * A list of the exception types that should not be reported.
 *
 * @var array
 */
protected $dontReport = [
    \Illuminate\Auth\AuthenticationException::class,
    \Illuminate\Auth\Access\AuthorizationException::class,
    \Symfony\Component\HttpKernel\Exception\HttpException::class,
    \Illuminate\Database\Eloquent\ModelNotFoundException::class,
    \Illuminate\Validation\ValidationException::class,
];

The Render Method

The render method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof CustomException) {
        return response()->view('errors.custom', [], 500);
    }

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

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);

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

abort(403, 'Unauthorized action.');

Custom HTTP Error Pages

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

Logging

Laravel provides a simple abstraction layer on top of the powerful Monolog library. By default, Laravel is configured to create a log file for your application in the storage/logs directory. You may write information to the logs using the Log facade:

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * Show the profile for the given user.
     *
     * @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)]);
    }
}

The logger provides the eight logging levels defined in RFC 5424: emergency, alert, critical, error, warning, notice, info and debug.

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

Contextual Information

An array of contextual data may also be passed to the log methods. This contextual data will be formatted and displayed with the log message:

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

Accessing The Underlying Monolog Instance

Monolog has a variety of additional handlers you may use for logging. If needed, you may access the underlying Monolog instance being used by Laravel:

$monolog = Log::getMonolog();

Search code, repositories, users, issues, pull requests…

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

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 [App\Office] 2",
    "exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
    ...
}

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 Illuminate\Database\Eloquent\ModelNotFoundException;

// ...

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 \GuzzleHttp\Client();
$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 GuzzleHttp\Exception\RequestException;

// ...

try {
    $client = new \GuzzleHttp\Client();
    $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 App\Exceptions;

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 \GuzzleHttp\Client();
    $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.

Понравилась статья? Поделить с друзьями:
  • Launcher код ошибки 805306369
  • Launcher exe системная ошибка геншин
  • Laravel вывод ошибок валидации
  • Laravel включить вывод ошибок
  • Laravel вернуть ajax ошибку