Yii2 api error handler

Yii includes a built-in error handler which makes error handling a much more pleasant experience than before. In particular, the Yii error handler does the following to improve error handling:

Yii includes a built-in error handler which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
    in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The error handler is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.

Using Error Handler ¶

The error handler is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:

use Yii;
use yiibaseErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Division by zero.");
}

// execution continues...

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an HTTP exception, such as yiiwebNotFoundHttpException. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.

use yiiwebNotFoundHttpException;

throw new NotFoundHttpException();

Customizing Error Display ¶

The error handler adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of yiibaseUserException, no call stack will be displayed regardless
the value of YII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.

By default, the error handler displays errors using two views:

  • @yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
    When YII_DEBUG is false, this is the only error view to be displayed.
  • @yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.

You can configure the errorView and exceptionView
properties of the error handler to use your own views to customize the error display.

Using Error Actions ¶

A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the errorAction property of the errorHandler
component like the following:

return [
    'components' => [
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
];

The errorAction property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.

You can create the site/error action as follows,

namespace appcontrollers;

use Yii;
use yiiwebController;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
        ];
    }
}

The above code defines the error action using the yiiwebErrorAction class which renders an error
using a view named error.

Besides using yiiwebErrorAction, you may also define the error action using an action method like the following,

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as yiiwebErrorAction:

  • name: the name of the error;
  • message: the error message;
  • exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
    error code, error call stack, etc.

Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.

Note: If you need to redirect in an error handler, do it the following way:

Yii::$app->getResponse()->redirect($url)->send();
return;

Customizing Error Response Format ¶

The error handler displays errors according to the format setting of the response.
If the response format is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the yiiwebResponse::$data property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the error response like the following:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

Обработка ошибок ¶

В состав Yii входит встроенный обработчик ошибок, делающий работу с ошибками гораздо более
приятным занятием. А именно:

  • Все не фатальные ошибки PHP (то есть warning, notice) конвертируются в исключения, которые можно перехватывать.
  • Исключения и фатальные ошибки PHP отображаются в режиме отладки с детальным стеком вызовов и исходным кодом.
  • Можно использовать для отображения ошибок действие контроллера.
  • Поддерживаются различные форматы ответа.

По умолчанию обработчик ошибок включен. Вы можете выключить его объявив константу
YII_ENABLE_ERROR_HANDLER со значением false во входном скрипте вашего приложения.

Использование обработчика ошибок ¶

Обработчик ошибок регистрируется в качестве компонента приложения
с именем errorHandler. Вы можете настраивать его следующим образом:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

С приведённой выше конфигурацией на странице ошибки будет отображаться до 20 строк исходного кода.

Как уже было упомянуто, обработчик ошибок конвертирует все не фатальные ошибки PHP в перехватываемые исключения.
Это означает что можно поступать с ошибками следующим образом:

use Yii;
use yiibaseErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Деление на ноль.");
}

// можно продолжать выполнение

Если вам необходимо показать пользователю страницу с ошибкой, говорящей ему о том, что его запрос не верен или не
должен был быть сделан, вы можете выкинуть исключение HTTP, такое как
yiiwebNotFoundHttpException. Обработчик ошибок корректно выставит статус код HTTP для ответа и использует
подходящий вид страницы ошибки.

use yiiwebNotFoundHttpException;
 
throw new NotFoundHttpException();

Настройка отображения ошибок ¶

Обработчик ошибок меняет отображение ошибок в зависимости от значения константы YII_DEBUG.
При YII_DEBUG равной true (режим отладки), обработчик ошибок будет отображать для облегчения отладки детальный стек
вызовов и исходный код. При YII_DEBUG равной false отображается только сообщение об ошибке, тем самым не позволяя
получить информацию о внутренностях приложения.

Информация: Если исключение является наследником yiibaseUserException, стек вызовов не отображается вне
зависимости от значения YII_DEBUG так как такие исключения считаются ошибками пользователя и исправлять что-либо
разработчику не требуется.

По умолчанию обработчик ошибок показывает ошибки используя два представления:

  • @yii/views/errorHandler/error.php: используется для отображения ошибок БЕЗ стека вызовов.
    При YII_DEBUG равной false используется только это преставление.
  • @yii/views/errorHandler/exception.php: используется для отображения ошибок СО стеком вызовов.

Вы можете настроить свойства errorView и exceptionView
для того, чтобы использовать свои представления.

Использование действий для отображения ошибок ¶

Лучшим способом изменения отображения ошибок является использование действий путём
конфигурирования свойства errorAction компонента errorHandler:

// ...
'components' => [
    // ...
    'errorHandler' => [
        'errorAction' => 'site/error',
    ],
]

Свойство errorAction принимает маршрут
действия. Конфигурация выше означает, что для отображения ошибки без стека вызовов будет использовано действие site/error.

Само действие можно реализовать следующим образом:

namespace appcontrollers;

use Yii;
use yiiwebController;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
        ];
    }
}

Приведённый выше код задаёт действие error используя класс yiiwebErrorAction, который рендерит ошибку используя
отображение error.

Вместо использования yiiwebErrorAction вы можете создать действие error как обычный метод:

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

Вы должны создать файл представления views/site/error.php. В этом файле, если используется yiiwebErrorAction,
вам доступны следующие переменные:

  • name: имя ошибки;
  • message: текст ошибки;
  • exception: объект исключения, из которого можно получить дополнительную информацию, такую как статус HTTP,
    код ошибки, стек вызовов и т.д.

Информация: Если вы используете шаблоны приложения basic или advanced,
действие error и файл представления уже созданы за вас.

Изменение формата ответа ¶

Обработчик ошибок отображает ошибки в соответствии с выбранным форматом ответа.
Если формат ответа задан как html, будут использованы представления для ошибок и
исключений, как описывалось ранее. Для остальных форматов ответа обработчик ошибок присваивает массив данных,
представляющий ошибку свойству yiiwebResponse::$data. Оно далее конвертируется в необходимый формат. Например,
если используется формат ответа json, вы получите подобный ответ:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

Изменить формат можно в обработчике события beforeSend компонента response в конфигурации приложения:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

Приведённый код изменит формат ответа на подобный:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

Handling Errors

Yii includes a built-in [[yiiwebErrorHandler|error handler]] which makes error handling a much more pleasant
experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines
    in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The [[yiiwebErrorHandler|error handler]] is enabled by default. You may disable it by defining the constant
YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.

Using Error Handler

The [[yiiwebErrorHandler|error handler]] is registered as an application component named errorHandler.
You may configure it in the application configuration like the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can
use the following code to deal with PHP errors:

use Yii;
use yiibaseErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Division by zero.");
}

// execution continues...

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply
throw an [[yiiwebHttpException|HTTP exception]], such as [[yiiwebNotFoundHttpException]]. The error handler
will correctly set the HTTP status code of the response and use an appropriate error view to display the error
message.

use yiiwebNotFoundHttpException;

throw new NotFoundHttpException();

Customizing Error Display

The [[yiiwebErrorHandler|error handler]] adjusts the error display according to the value of the constant YII_DEBUG.
When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call
stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error
message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of [[yiibaseUserException]], no call stack will be displayed regardless
the value of YII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the
developers do not need to fix anything.

By default, the [[yiiwebErrorHandler|error handler]] displays errors using two views:

  • @yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information.
    When YII_DEBUG is false, this is the only error view to be displayed.
  • @yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.

You can configure the [[yiiwebErrorHandler::errorView|errorView]] and [[yiiwebErrorHandler::exceptionView|exceptionView]]
properties of the error handler to use your own views to customize the error display.

Using Error Actions

A better way of customizing the error display is to use dedicated error actions.
To do so, first configure the [[yiiwebErrorHandler::errorAction|errorAction]] property of the errorHandler
component like the following:

return [
    'components' => [
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
];

The [[yiiwebErrorHandler::errorAction|errorAction]] property takes a route
to an action. The above configuration states that when an error needs to be displayed without call stack information,
the site/error action should be executed.

You can create the site/error action as follows,

namespace appcontrollers;

use Yii;
use yiiwebController;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
        ];
    }
}

The above code defines the error action using the [[yiiwebErrorAction]] class which renders an error
using a view named error.

Besides using [[yiiwebErrorAction]], you may also define the error action using an action method like the following,

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

You should now create a view file located at views/site/error.php. In this view file, you can access
the following variables if the error action is defined as [[yiiwebErrorAction]]:

  • name: the name of the error;
  • message: the error message;
  • exception: the exception object through which you can retrieve more useful information, such as HTTP status code,
    error code, error call stack, etc.

Info: If you are using the basic project template or the advanced project template,
the error action and the error view are already defined for you.

Note: If you need to redirect in an error handler, do it the following way:

Yii::$app->getResponse()->redirect($url)->send();
return;

Customizing Error Response Format

The error handler displays errors according to the format setting of the response.
If the [[yiiwebResponse::format|response format]] is html, it will use the error or exception view
to display errors, as described in the last subsection. For other response formats, the error handler will
assign the array representation of the exception to the [[yiiwebResponse::data]] property which will then
be converted to different formats accordingly. For example, if the response format is json, you may see
the following response:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

You may customize the error response format by responding to the beforeSend event of the response component
in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the error response like the following:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

When handling a RESTful API request, if there is an error in the user request or if something unexpected
happens on the server, you may simply throw an exception to notify the user that something went wrong.
If you can identify the cause of the error (e.g., the requested resource does not exist), you should
consider throwing an exception along with a proper HTTP status code (e.g., [[yiiwebNotFoundHttpException]]
represents a 404 status code). Yii will send the response along with the corresponding HTTP status
code and text. Yii will also include the serialized representation of the
exception in the response body. For example:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

The following list summarizes the HTTP status code that are used by the Yii REST framework:

  • 200: OK. Everything worked as expected.
  • 201: A resource was successfully created in response to a POST request. The Location header
    contains the URL pointing to the newly created resource.
  • 204: The request was handled successfully and the response contains no body content (like a DELETE request).
  • 304: The resource was not modified. You can use the cached version.
  • 400: Bad request. This could be caused by various actions by the user, such as providing invalid JSON
    data in the request body, providing invalid action parameters, etc.
  • 401: Authentication failed.
  • 403: The authenticated user is not allowed to access the specified API endpoint.
  • 404: The requested resource does not exist.
  • 405: Method not allowed. Please check the Allow header for the allowed HTTP methods.
  • 415: Unsupported media type. The requested content type or version number is invalid.
  • 422: Data validation failed (in response to a POST request, for example). Please check the response body for detailed error messages.
  • 429: Too many requests. The request was rejected due to rate limiting.
  • 500: Internal server error. This could be caused by internal program errors.

Customizing Error Response

Sometimes you may want to customize the default error response format. For example, instead of relying on
using different HTTP statuses to indicate different errors, you would like to always use 200 as HTTP status
and enclose the actual HTTP status code as part of the JSON structure in the response, like shown in the following,

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

To achieve this goal, you can respond to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null && !empty(Yii::$app->request->get('suppress_response_code'))) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the response (for both successful and failed responses) as explained when
suppress_response_code is passed as a GET parameter.

Включаем/выключаем сообщения об ошибках

В Yii2 обработчик ошибок по умолчанию включен. Отключить его можно следующим образом, откройте файл @app/web/index.php и добавьте следующий код:

// Yii2 отключить error handler
define('YII_ENABLE_ERROR_HANDLER', false);

Настройки по умолчанию

По умолчанию в Yii2 уже есть готовый к использованию обработчик ошибок.

Обработчик ошибок в Yii2 называется errorHandler. Его настройки находятся в:

  • для Yii basic — yourProject/config/web.php
  • Yii advanced — yourProject/common|backend|frontend/config/main.php

Например, по умолчанию обработчик ошибок использует действие site/error для вывода ошибок и исключений:

return [
    // ...
    'components' => [
        // ...
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        // ...
    ],
    // ...
];

В таком случае нет необходимости описывать действие error в контроллере SiteController. Т.к. Yii2 использует ErrorAction по умолчанию, который вшит в фреймворк. SiteController.php:

class SiteController extends Controller
{
    // ...
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
            // ...
        ];
    }
    // ...
}

По умолчанию yiiwebErrorAction будет использовать для вывода ошибок представление (view): yourProject/views/site/error.php

Настройка представления (view) при конфигурации по умолчанию

Предположим, что используется конфигурация по умолчанию. В yourProject/config/web.php или yourProject/frontend|backend/config/main.php:

return [
    // ...
    'components' => [
        // ...
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
        // ...
    ],
    // ...
];

В контроллере SiteController приложения yourProject/controllers/SiteController.php:

class SiteController extends Controller
{
    // ...
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
            // ...
        ];
    }
    // ...
}

Кастомизируем представление (view) вывода ошибок

Использовать свое представление (view) для вывода ошибки очень просто, достаточно добавить путь к view в настройки SiteController метод actions элемент массива error. Он будет перекрывать свойства yiiwebErrorAction, файл SiteController.php:

class SiteController extends Controller
{
    // ...
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
                'view' => '@app/views/site/myerror.php'
            ],
            // ...
        ];
    }
    // ...
}

Кастомизируем layout вывода ошибок

Для решения этой задачи у нас есть 2 варианта.

1-й вариант

Указать расположение представления (view) об ошибке напрямую. Например назначить отдельный layout для вывода view ошибки:

// Your error view yourErrorView.php
$this->context->layout = 'error_layout';

2-й вариант

Назначить layout для ошибок в методе beforeAction контроллера SiteController, SiteController.php:

public function beforeAction($action)
{
    if ($action->id == 'error') {
        $this->layout = 'error_layout';
    }
    return parent::beforeAction($action);
}

Использование кастомизированого действия (action) для вывода ошибок

Так же вы можете написать свой собственный метод действия обработки ошибок и использовать собственное view или layout для отображения информации об ошибке.

Например создайте действие myerror в контроллере SiteController и используйте его как метод обработки ошибок, SiteController.php:

class SiteController extends Controller
{
    // ...
    public function actionMyerror()
    {
        $exception = Yii::$app->errorHandler->exception;
        if ($exception !== null) {
            $statusCode = $exception->statusCode;
            $name = $exception->getName();
            $message = $exception->getMessage();
            $this->layout = 'your_error_layout';
            return $this->render('yourErrorView', [
                'exception' => $exception,
                'statusCode' => $statusCode,
                'name' => $name,
                'message' => $message
            ]);
        }
    }
}

Далее закоментируйте или удалите елемент error возвращаемого массива метода actions, SiteController.php:

class SiteController extends Controller
{
    // ...
    public function actions()
    {
        return [            
            // 'error' => [
            //    'class' => 'yiiwebErrorAction',
            //    'view' => '@app/views/site/YOUR_ERROR_VIEW.php'
            // ],
            // ...
        ];
    }
    // ...
}

И последнее, укажите котроллер и действие для обработки ошибок в конфигурации приложения yourProject/config/web.php или yourProject/common|backend|frontend/config/main.php:

return [
    // ...
    'components' => [
        // ...
        'errorHandler' => [
            'errorAction' => 'site/myerror',
        ],
        // ...
    ],
    // ...
];

Теперь Yii2 будет использовать действие site/myerror указанные в нем loyout и view для вывода ошибок.

  1. Using Error Handler
  2. Customizing Error Display

Yii includes a built-in error handler which makes error handling a much more pleasant experience than before. In particular, the Yii error handler does the following to improve error handling:

  • All non-fatal PHP errors (e.g. warnings, notices) are converted into catchable exceptions.
  • Exceptions and fatal PHP errors are displayed with detailed call stack information and source code lines in debug mode.
  • Supports using a dedicated controller action to display errors.
  • Supports different error response formats.

The error handler is enabled by default. You may disable it by defining the constant YII_ENABLE_ERROR_HANDLER to be false in the entry script of your application.

Using Error Handler

The error handler is registered as an application component named errorHandler. You may configure it in the application configuration like the following:

return [
    'components' => [
        'errorHandler' => [
            'maxSourceLines' => 20,
        ],
    ],
];

With the above configuration, the number of source code lines to be displayed in exception pages will be up to 20.

As aforementioned, the error handler turns all non-fatal PHP errors into catchable exceptions. This means you can use the following code to deal with PHP errors:

use Yii;
use yiibaseErrorException;

try {
    10/0;
} catch (ErrorException $e) {
    Yii::warning("Division by zero.");
}

// execution continues...

If you want to show an error page telling the user that his request is invalid or unexpected, you may simply throw an HTTP exception, such as yiiwebNotFoundHttpException. The error handler will correctly set the HTTP status code of the response and use an appropriate error view to display the error message.

use yiiwebNotFoundHttpException;

throw new NotFoundHttpException();

Customizing Error Display

The error handler adjusts the error display according to the value of the constant YII_DEBUG. When YII_DEBUG is true (meaning in debug mode), the error handler will display exceptions with detailed call stack information and source code lines to help easier debugging. And when YII_DEBUG is false, only the error message will be displayed to prevent revealing sensitive information about the application.

Info: If an exception is a descendant of yiibaseUserException, no call stack will be displayed regardless the value of YII_DEBUG. This is because such exceptions are considered to be caused by user mistakes and the developers do not need to fix anything.

By default, the error handler displays errors using two views:

  • @yii/views/errorHandler/error.php: used when errors should be displayed WITHOUT call stack information. When YII_DEBUG is false, this is the only error view to be displayed.
  • @yii/views/errorHandler/exception.php: used when errors should be displayed WITH call stack information.

You can configure the errorView and exceptionView properties of the error handler to use your own views to customize the error display.

Using Error Actions

A better way of customizing the error display is to use dedicated error actions. To do so, first configure the errorAction property of the errorHandler component like the following:

return [
    'components' => [
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ]
];

The errorAction property takes a route to an action. The above configuration states that when an error needs to be displayed without call stack information, the site/error action should be executed.

You can create the site/error action as follows,

namespace appcontrollers;

use Yii;
use yiiwebController;

class SiteController extends Controller
{
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction',
            ],
        ];
    }
}

The above code defines the error action using the yiiwebErrorAction class which renders an error using a view named error.

Besides using yiiwebErrorAction, you may also define the error action using an action method like the following,

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

You should now create a view file located at views/site/error.php. In this view file, you can access the following variables if the error action is defined as yiiwebErrorAction:

  • name: the name of the error;
  • message: the error message;
  • exception: the exception object through which you can retrieve more useful information, such as HTTP status code, error code, error call stack, etc.

Info: If you are using the basic project template or the advanced project template, the error action and the error view are already defined for you.

Note: If you need to redirect in an error handler, do it the following way:

Yii::$app->getResponse()->redirect($url)->send();
return;

Customizing Error Response Format

The error handler displays errors according to the format setting of the response. If the response format is html, it will use the error or exception view to display errors, as described in the last subsection. For other response formats, the error handler will assign the array representation of the exception to the yiiwebResponse::$data property which will then be converted to different formats accordingly. For example, if the response format is json, you may see the following response:

HTTP/1.1 404 Not Found
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "name": "Not Found Exception",
    "message": "The requested resource was not found.",
    "code": 0,
    "status": 404
}

You may customize the error response format by responding to the beforeSend event of the response component in the application configuration:

return [
    // ...
    'components' => [
        'response' => [
            'class' => 'yiiwebResponse',
            'on beforeSend' => function ($event) {
                $response = $event->sender;
                if ($response->data !== null) {
                    $response->data = [
                        'success' => $response->isSuccessful,
                        'data' => $response->data,
                    ];
                    $response->statusCode = 200;
                }
            },
        ],
    ],
];

The above code will reformat the error response like the following:

HTTP/1.1 200 OK
Date: Sun, 02 Mar 2014 05:31:43 GMT
Server: Apache/2.2.26 (Unix) DAV/2 PHP/5.4.20 mod_ssl/2.2.26 OpenSSL/0.9.8y
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8

{
    "success": false,
    "data": {
        "name": "Not Found Exception",
        "message": "The requested resource was not found.",
        "code": 0,
        "status": 404
    }
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Yii2 activerecord save error
  • Yii2 activeform error options
  • Yii2 500 internal server error
  • Yii2 404 error
  • Yii log error

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии