Yii2 вывести сообщение об ошибке

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

В состав 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
    }
}

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.

Customizing Error Response Format

The error handler displays errors according to the format setting of the response.
If the 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
    }
}

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

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

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

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

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

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

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

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

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

use Yii;
use yiibaseErrorException;

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

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

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

use yiiwebNotFoundHttpException;
 
throw new NotFoundHttpException();

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

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

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

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

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

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

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

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

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

Свойство [[yiiwebErrorHandler::errorAction|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,
    код ошибки, стек вызовов и т.д.

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

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

Обработчик ошибок отображает ошибки в соответствии с выбранным форматом ответа.
Если [[yiiwebResponse::format|формат ответа]] задан как 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
    }
}

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 входит встроенный [[yiiwebErrorHandler|обработчик ошибок]], делающий работу с ошибками гораздо более
приятным занятием. А именно:

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

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

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

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

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

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

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

use Yii;
use yiibaseErrorException;

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

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

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

use yiiwebNotFoundHttpException;
 
throw new NotFoundHttpException();

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

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

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

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

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

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

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

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

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

Свойство [[yiiwebErrorHandler::errorAction|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,
    код ошибки, стек вызовов и т.д.

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

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

Обработчик ошибок отображает ошибки в соответствии с выбранным форматом ответа.
Если [[yiiwebResponse::format|формат ответа]] задан как 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
    }
}

Обработка ошибок в Yii2. (Errors, ErrorHandler, HttpException)

Конкретный пример

В действии запланирована такая выдача ошибки 403

если всё хорошо, то выполняется что должно выполняться
} else {
    throw new HttpException(403,'Доступно для зарегистрировавшихся');
}

Хочу, чтобы вместо этого пользователя перекидывало на страницу с формой входа. Если использовать yii-user, там можно ещё передать флеш-сообщение с каким-то сопутствующим текстом и оно будет показано перед формой.

если всё хорошо, то выполняется что должно выполняться
} else {
    Yii::$app->session->setFlash('info', 'Курс доступен только для зарегистрированных пользователей. Войдите в личный кабинет или пройдите регистрацию, если ещё не сделали этого.');
    return $this->redirect('/user/login');
}

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

Обработчик ошибок включен в Yii2 по-умолчанию. его можно отключить во входном скрипте web/index.php

// Отключение обработчика ошибок Yii2
define('YII_ENABLE_ERROR_HANDLER', false);

Обработчик ошибок подключён как компонент приложения в конфиге

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

В SiteController.php использовано встроенное действие yiiwebErrorAction, которое отображает ошибки через представление views/site/error.php

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

Представление это можно заменить, указав свойство ‘view’

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

Можно изменить шаблон для вывода сообщений об ошибках 2 способами:

1. Явно указать нужный шаблон в файле представления

$this->context->layout = 'custom-error-layout';

2. Указать шаблон в методе beforeAction() контроллера SiteController

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

Создать свой обработчик ошибок

Создадим действие site/fault в контроллере SiteController

public function actionFault()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        $statusCode = $exception->statusCode;
        $name = $exception->getName();
        $message = $exception->getMessage();
        $this->layout = 'custom-error-layout';
        return $this->render('custom-error-view', [
            'exception' => $exception,
            'statusCode' => $statusCode,
            'name' => $name,
            'message' => $message
        ]);
    }
}

Тогда в конфиге надо заменить на

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

Теперь все ошибки будут обрабатываться новым методом actionFault(). Можно удалить описание ненужного здесь встроенного действия.

class SiteController extends Controller
{
    // ...
    public function actions()
    {
        return [
             // Comment out or remove following error configuration
            // 'error' => [
            //    'class' => 'yiiwebErrorAction',
            //    'view' => '@app/views/site/custom-error-view.php'
            // ],
            // ...
        ];
    }
    // ...
}

По мотивам – http://nix-tips.ru/yii-2.html

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 followings 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 application template or the advanced application template,
the error action and the error view are already defined for you.

Customizing Error Response Format

The error handler displays errors according to the format setting of the response.
If the 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
    }
}

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 followings 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 application template or the advanced application template,
the error action and the error view are already defined for you.

Customizing Error Response Format

The error handler displays errors according to the format setting of the response.
If the 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
    }
}

Вступление

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

В чём разница между ошибками и исключениями?

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

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

Как эти процессы протекают в Yii?

В Yii, не фатальные PHP ошибки (заметки и предупреждения) отлавливаются, что даёт возможность должным образом на них среагировать. Все эти исключения могут направляться на определённый экшен контроллера. Также вы можете повлиять на формат отображения данных ошибок: HTML, JSON, XML и т.д.

Исключения и фатальные PHP ошибки можно увидеть только если код работает в отладочном режиме. В этом случае Yii выведет всю подробную информацию об ошибке, включая фрагмент проблемного кода (пример показан в ковер-изображении к данному уроку).

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

К примеру:

$t = new Unknownobject();

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

Конфигурация обработчика ошибок и исключений

Для начала нам нужно внести кое-какие записи в файл конфигурации frontend/config/main.php. Как показано ниже, в этом файле определён компонент errorHandler. Взгляните на конфигурацию errorHandler в разделе components:

<?php
$params = array_merge(
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);
return [
    'id' => 'mp-frontend',
    'name' => 'Meeting Planner',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log','commoncomponentsSiteHelper'],
    'controllerNamespace' => 'frontendcontrollers',
    'catchAll'=> [],
    'components' => [
      'assetManager' => [...],
      ...
      'errorHandler' => [
            'errorAction' => 'site/error',
            'maxSourceLines' => 20,
        ],
        ...
    ],
];

В вышеприведённом примере определено, что при возникновении ошибки errorAction направит пользователя на экшен error SiteController-а.

Если более подробно, то Yii предлагает целый ряд конфигурационных настроек к компоненту errorHandler для редиректа и обработки информации:

Свойство Тип Описание
$callStackItemView строка Путь к файлу, в котором будет происходить рендеринг информации об ошибках. Пример: ‘@yii/views/errorHandler/callStackItem.php’
$displayVars массив Список определённых PHP переменных, которые должны отображаться в специальной секции отображения ошибок. Примеру: [‘_GET’, ‘_POST’, ‘_FILES’, ‘_COOKIE’, ‘_SESSION’]
$errorAction строка Маршрут (site/error) к контроллеру и экшену в котором будут обрабатываться ошибки.
$errorView строка Путь к файлу, в котором будет происходить рендеринг информации об ошибках без подробного описания. Пример: ‘@yii/views/errorHandler/error.php’
$exceptionView строка Путь к файлу, в котором будет происходить рендеринг информации об исключениях. Пример: ‘@yii/views/errorHandler/exception.php’
$maxSourceLines число Максимальное число отображаемого исходного кода.
$maxTraceSourceLines число Максимальное число отображаемого исходного трэйс-кода.
$previousExceptionView строка Путь к файлу, в котором будет происходить рендеринг информации о предыдущем исключении. Пример: ‘@yii/views/errorHandler/previousException.php’

Прямой вызов errorActions

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

Как раз-таки это и происходит в экшене errorAction класса errorHandler. С этой точки мы и будем направлены на SiteController -> actionError:

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

Определим экшен error в SiteController:

namespace appcontrollers;

use Yii;
use yiiwebController;

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

Вот так вот будет выглядеть обработка ошибки (ссылка на более подробную информацию):

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

Также вы можете точно определить, возникла ли ошибка или в вашем приложении не существует запрашиваемого маршрута:

public function actionError()
{
    $exception = Yii::$app->errorHandler->exception;
    if ($exception instanceof yiiwebNotFoundHttpException) {
        // all non existing controllers+actions will end up here
        return $this->render('pnf'); // page not found
    } else {
      return $this->render('error', ['exception' => $exception]);
    }
}

Вот мой обработчик ошибки Page Not Found 404:

Никто не запрещает на странице описания ошибки оставить свои контакты или показать материалы схожие с пользовательским запросом. Все эти меры увеличивают шансы сохранить своё лицо перед пользователем.

Вот моя страница с отображением ошибки (конечно же над ней нужно ещё работать и работать):

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

Для обработки исключений можем воспользоваться PHP-шной конструкцией try catch. Давайте посмотрим пример в котором разделим число на ноль:

use Yii;
use yiibaseErrorException;

...

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

...

В блоке catch запишем предупреждение в лог. В Yii есть несколько методов логирования:

  • Yii::trace(): сообщение с куском кода. Обычно используется во время разработки.
  • Yii::info(): информационное сообщение.
  • Yii::warning(): предупреждение о каком-то событии
  • Yii::error(): сообщение о фатальной ошибке

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

use yiiwebNotFoundHttpException;

throw new NotFoundHttpException();

Вот пример в котором мы выбрасываем исключение с определённым HTTP кодом и специальным сообщением:

try {
    10/0;
} catch (ErrorException $e) {
  throw new yiiwebHttpException(451,
      'Tom McFarlin's humor is often lost on me
          (and lots of people).');
}

А вот что в этом случае увидит пользователь:

О логировании в Yii

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

Заключение

Надеюсь, что мне удалось раскрыть тему, и должным образом показать процесс обработки ошибок и исключений.

Вступление

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

Не знакомы с Yii? Наверстать упущенное можно, прочитав статью Знакомство с фрэймворком Yii и серию Разработка на базе Yii2.

В чём разница между ошибками и исключениями?

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

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

Как эти процессы протекают в Yii?

В Yii, не фатальные PHP ошибки (заметки и предупреждения) отлавливаются, что даёт возможность должным образом на них среагировать.  Все эти исключения могут направляться на определённый экшен контроллера. Также вы можете повлиять на  формат отображения данных ошибок: HTML, JSON, XML и т.д.

Исключения и фатальные PHP ошибки можно увидеть только если код работает в отладочном режиме. В этом случае Yii выведет всю подробную информацию об ошибке, включая фрагмент проблемного кода (пример показан в ковер-изображении к данному уроку).

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

К примеру:

1
$t = new Unknownobject();

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

Конфигурация обработчика ошибок и исключений

Для начала нам нужно внести кое-какие записи в файл конфигурации frontend/config/main.php. Как показано ниже, в этом файле определён компонент errorHandler. Данный пример взят из моей серии по организации стартапа Meeting Planner. Взгляните на конфигурацию  errorHandler в разделе components:

1
<?php
2
$params = array_merge(
3
    require(__DIR__ . '/params.php'),
4
    require(__DIR__ . '/params-local.php')
5
);
6
return [
7
    'id' => 'mp-frontend',
8
    'name' => 'Meeting Planner',
9
    'basePath' => dirname(__DIR__),
10
    'bootstrap' => ['log','commoncomponentsSiteHelper'],
11
    'controllerNamespace' => 'frontendcontrollers',
12
    'catchAll'=> [],
13
    'components' => [
14
      'assetManager' => [...],
15
      ...
16
      'errorHandler' => [
17
            'errorAction' => 'site/error',
18
            'maxSourceLines' => 20,
19
        ],
20
        ...
21
    ],
22
];

В вышеприведённом примере определено, что при возникновении ошибки errorAction направит пользователя на экшен error SiteController-а.

Если более подробно, то Yii предлагает целый ряд конфигурационных настроек к компоненту errorHandler для редиректа и обработки информации:

Свойство Тип Описание
$callStackItemView строка Путь к файлу, в котором будет происходить рендеринг информации об ошибках. Пример: ‘@yii/views/errorHandler/callStackItem.php’
$displayVars массив Список определённых PHP переменных, которые должны отображаться в специальной секции отображения ошибок. Примеру: [‘_GET’, ‘_POST’, ‘_FILES’, ‘_COOKIE’, ‘_SESSION’]
$errorAction строка Маршрут (site/error) к контроллеру и экшену в котором будут обрабатываться ошибки.
$errorView строка Путь к файлу, в котором будет происходить рендеринг информации об ошибках без подробного описания. Пример: ‘@yii/views/errorHandler/error.php’
$exceptionView строка Путь к файлу, в котором будет происходить рендеринг информации об исключениях. Пример: ‘@yii/views/errorHandler/exception.php’
$maxSourceLines число Максимальное число отображаемого исходного кода.
$maxTraceSourceLines число Максимальное число отображаемого исходного трэйс-кода.
$previousExceptionView строка Путь к файлу, в котором будет происходить рендеринг информации о предыдущем исключении. Пример: ‘@yii/views/errorHandler/previousException.php’

Прямой вызов errorActions

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

Как раз-таки это и происходит в экшене errorAction класса errorHandler. С этой точки мы и будем направлены на SiteController -> actionError:

1
return [
2
    'components' => [
3
        'errorHandler' => [
4
            'errorAction' => 'site/error',
5
        ],
6
    ]
7
];

Определим экшен error в SiteController:

1
namespace appcontrollers;
2

3
use Yii;
4
use yiiwebController;
5

6
class SiteController extends Controller
7
{
8
    public function actions()
9
    {
10
        return [
11
            'error' => [
12
                'class' => 'yiiwebErrorAction',
13
            ],
14
        ];
15
    }
16
}

Вот так вот будет выглядеть обработка ошибки (ссылка на более подробную информацию):

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

Также вы можете точно определить, возникла ли ошибка или в вашем приложении не существует запрашиваемого маршрута:

1
public function actionError()
2
    {
3
        $exception = Yii::$app->errorHandler->exception;
4
        if ($exception instanceof yiiwebNotFoundHttpException) {
5
            // all non existing controllers+actions will end up here

6
            return $this->render('pnf'); // page not found

7
        } else {
8
          return $this->render('error', ['exception' => $exception]);
9
        }
10
    }

Вот мой обработчик ошибки Page Not Found 404:

Yii2 Error Handling and Exceptions 404 Page Not Found ErrorYii2 Error Handling and Exceptions 404 Page Not Found ErrorYii2 Error Handling and Exceptions 404 Page Not Found Error

Никто не запрещает на странице описания ошибки оставить свои контакты или показать материалы схожие с пользовательским запросом. Все эти меры увеличивают шансы сохранить своё лицо перед пользователем.

Вот моя страница с отображением ошибки (конечно же над ней нужно ещё работать и работать):

Yii2 Error Handling and Exceptions Typical Page ErrorYii2 Error Handling and Exceptions Typical Page ErrorYii2 Error Handling and Exceptions Typical Page Error

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

Для обработки исключений можем воспользоваться PHP-шной конструкцией try catch. Давайте посмотрим пример в котором разделим число на ноль:

1
use Yii;
2
use yiibaseErrorException;
3

4
...
5

6
    try {
7
        10/0;
8
    } catch (ErrorException $e) {
9
        Yii::warning("Division by zero.");
10
    }
11
    
12
...

В блоке catch запишем предупреждение в лог. В Yii есть несколько методов логирования:

  • Yii::trace(): сообщение с куском кода. Обычно используется во время разработки.
  • Yii::info(): информационное сообщение.
  • Yii::warning(): предупреждение о каком-то событии.
  • Yii::error(): сообщение о фатальной ошибке.

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

1
use yiiwebNotFoundHttpException;
2

3
throw new NotFoundHttpException();

Вот пример в котором мы выбрасываем исключение с определённым  HTTP кодом и специальным сообщением:

1
  try {
2
          10/0;
3
      } catch (ErrorException $e) {
4
        throw new yiiwebHttpException(451,
5
            'Tom McFarlin's humor is often lost on me

6
                (and lots of people).');
7
    }

А вот что в этом случае увидит пользователь:

Yii2 Error Handling and Exceptions Throw an exceptionYii2 Error Handling and Exceptions Throw an exceptionYii2 Error Handling and Exceptions Throw an exception

О логировании в Yii

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

Заключение

Надеюсь, что мне удалось раскрыть тему, и должным образом показать процесс обработки ошибок и исключений. Следите за обновлениями серии Разработка на базе Yii2, где мы затрагиваем различные аспекты работы с фрэймворком.

Если же вы хотите более глубоко нырнуть в изучении Yii, то советую ознакомиться с серией по Созданию стартапа на PHP, где активно используется компонент шаблонизатора Yii2.  В данной серии описаны все этапы создания сервиса Meeting Planner. Для тех кто только начинает учить Yii — данный материал будет очень полезен.

Если вы хотите первыми узнать о выходе новых уроков по Yii2 подписывайтесь на мой Twitter @lookahead_io и персональную страницу.

Похожие материалы

  • Документация по yiiwebErrorHandler
  • Обработка ошибок (Руководство по Yii 2.0)
  • Логирование (Руководство по Yii 2.0)
  • Обмен опытом по работе с Yii2 (сайт автора)

  • Yes of course not ошибка
  • Yealink zadarma ошибка регистрации
  • Yealink w52p ошибка регистрации трубки
  • Yealink t21p e2 ошибка регистрации
  • Yealink t21 e2 ошибка регистрации аккаунта