Yii2 error page

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

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

// Отключить ErrorHandler
define('YII_ENABLE_ERROR_HANDLER', false);

Данный компонент подключён в конфиге приложения (@app/config/web.php):

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

За рендер самой страницы ошибки отвечает экшен указанный в параметре компонента errorAction. 

В контроллере (SiteController) определён ErrorAction:

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

Путь к файлу вида для данного экшена @app/views/site/error.php

Изменить представление вывода ошибок можно в свойстве view класса yiiwebErrorAction:

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

Свой обработчик ошибок

При необходимости, можно создать собственный метод для обработки ошибок. Например, создадим контроллер ErrorController и метод actionFault() в нём:

<?php
namespace appcontrollers;
use Yii;
use yiiwebController;

/**
 * Class ErrorController
 * Custom error handler
 */
class ErrorController extends Controller
{
  /**
   * @return bool|string
   */
  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';
      // error/fault
      return $this->render('fault', [
          'exception' => $exception,
          'statusCode' => $statusCode,
          'name' => $name,
          'message' => $message
      ]);
    }
    return false;
  }
}

Создадим кастомное представление (@app/views/error/fault.php):

<?php
/* @var $this yiiwebView */
/* @var $exception; === стек */
/* @var $statusCode; === код ошибки  */
/* @var $name; === имя ошибки  */
/* @var $message; === текс ошибка */

use yiihelpersHtml;
$this->title = $message;
?>
<!-- Выводим то, что нам необходимо -->
<div class="error">
    <h2 class="statusCode"><?= nl2br(Html::encode($statusCode)) ?></h2>
    <p class="statusName"><?= nl2br(Html::encode($name)) ?></p>
    <p class="statusMessage"><?= nl2br(Html::encode($message)) ?></p>
    <p class="statusException"><?= nl2br(Html::encode($exception)) ?></p>
</div>

Далее стилизовать страницу можно как угодно.

Немного поправить конфиг (изменить путь к обработчику):

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

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

class SiteController extends Controller
{  
  public function actions()
  {
    return [
    	// Обработкой ошибок теперь занимается другой метод (error/fault)
    ];
  }
  
}

Способов переопределения больше, я же показал один из самых простых.

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

If you are trying to customize an Error page and want to get the errors code separately inside the view then you have the $exception,$name and $message variables available inside the view, but in case if you use yiiwebErrorAction, before I go ahead you need to see in which category you fall.

CASE 1 Using yiiwebErrorAction

  1. Inside your PageController you should have an actions() function like below.

    public function actions() {
        return [
            'error' => [
                'class' => 'yiiwebErrorAction' ,
            ] 
        ];
    }
    
  2. If you haven’t created a separate layout for error add one now, it better to keep your error layout separate. Just copy the layouts/main.php and remove all extra CSS and js files or create frontend/assets/ErrorAsset.php and register on top of your layout file.

  3. Add beforeAction() function inside your PageController like below.

    Sample Code

    public function beforeAction( $action ) {
        if ( parent::beforeAction ( $action ) ) {
    
             //change layout for error action after 
             //checking for the error action name 
             //so that the layout is set for errors only
            if ( $action->id == 'error' ) {
                $this->layout = 'error';
            }
            return true;
        } 
    }
    
  4. Now as you have specified the 'page/error' inside your errorHandler component’s config so the action name would be error and so would be the view file, this view file should be inside the page folder this should be the path page/error.php. You have the $exception variable available which holds the exception object in your case yiiwebNotFoundHttpException Object. and you can call $exception->statusCode to check which status code has been thrown for the exception, in your case, it would show 404.


CASE 2 Using Custom Action for displaying Errors

Another Way is to use custom action inside the controller rather than using the yiiwebErrorAction in that case you do not need to add the actions() function and inside your custom error function you should call

$exception  =   Yii::$app->getErrorHandler()->exception; 

and use the $exception->statusCode. Make sure you check for the exact action name for inside your beforeAction() function change your check accordingly for the line

if ( $action->id == 'error' ) {

CASE 3 SHUTUP just Give me the Exception

If you don’t want any of above and just want to check the Exception code inside the controller’s beforeAction() you have to access the same exception object above but with a shorthand via config’s erorHandler component.

public function beforeAction($action) {

    $exception = Yii::$app->getErrorHandler()->exception;

    if(parent::beforeAction($action)) {
        $hasError = $action->id == 'error' && $exception !== NULL;

        if($hasError) {
            echo $exception->statusCode;
            return false;
        }
    }
    return true;
}

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

Содержание

  1. Обработка ошибок ¶
  2. Использование обработчика ошибок ¶
  3. Настройка отображения ошибок ¶
  4. Использование действий для отображения ошибок ¶
  5. Изменение формата ответа ¶
  6. Handling Errors ¶
  7. Using Error Handler ¶
  8. Customizing Error Display ¶
  9. Using Error Actions ¶
  10. Customizing Error Response Format ¶
  11. Name already in use
  12. yii2 / docs / guide-ru / runtime-handling-errors.md
  13. Abstract Class yiibaseErrorHandler
  14. Public Properties
  15. Public Methods
  16. Protected Methods
  17. Events
  18. Property Details

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

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

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

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

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

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

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

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

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

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

Обработчик ошибок меняет отображение ошибок в зависимости от значения константы 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 :

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

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

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

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

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

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

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

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

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

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

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

Источник

Handling Errors ¶

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:

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:

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.

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:

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,

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,

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:

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:

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

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

Источник

Name already in use

yii2 / docs / guide-ru / runtime-handling-errors.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Источник

Abstract Class yiibaseErrorHandler

Inheritance yiibaseErrorHandler » yiibaseComponent » yiibaseBaseObject
Implements yiibaseConfigurable
Subclasses yiiconsoleErrorHandler, yiiwebErrorHandler
Available since version 2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/base/ErrorHandler.php

ErrorHandler handles uncaught PHP errors and exceptions.

ErrorHandler is configured as an application component in yiibaseApplication by default. You can access that instance via Yii::$app->errorHandler .

For more details and usage information on ErrorHandler, see the guide article on handling errors.

Public Properties

Property Type Description Defined By
$behaviors yiibaseBehavior[] List of behaviors attached to this component. yiibaseComponent
$discardExistingOutput boolean Whether to discard any existing page output before error display. yiibaseErrorHandler
$exception Throwable|null The exception that is being handled currently. yiibaseErrorHandler
$memoryReserveSize integer The size of the reserved memory. yiibaseErrorHandler
$silentExitOnException boolean If true — handleException() will finish script with ExitCode::OK . yiibaseErrorHandler

Public Methods

Method Description Defined By
__call() Calls the named method which is not a class method. yiibaseComponent
__clone() This method is called after the object is created by cloning an existing one. yiibaseComponent
__construct() Constructor. yiibaseBaseObject
__get() Returns the value of a component property. yiibaseComponent
__isset() Checks if a property is set, i.e. defined and not null. yiibaseComponent
__set() Sets the value of a component property. yiibaseComponent
__unset() Sets a component property to be null. yiibaseComponent
attachBehavior() Attaches a behavior to this component. yiibaseComponent
attachBehaviors() Attaches a list of behaviors to the component. yiibaseComponent
behaviors() Returns a list of behaviors that this component should behave as. yiibaseComponent
canGetProperty() Returns a value indicating whether a property can be read. yiibaseComponent
canSetProperty() Returns a value indicating whether a property can be set. yiibaseComponent
className() Returns the fully qualified name of this class. yiibaseBaseObject
clearOutput() Removes all output echoed before calling this method. yiibaseErrorHandler
convertExceptionToError() Converts an exception into a PHP error. yiibaseErrorHandler
convertExceptionToString() Converts an exception into a simple string. yiibaseErrorHandler
convertExceptionToVerboseString() Converts an exception into a string that has verbose information about the exception and its trace. yiibaseErrorHandler
detachBehavior() Detaches a behavior from the component. yiibaseComponent
detachBehaviors() Detaches all behaviors from the component. yiibaseComponent
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. yiibaseComponent
getBehavior() Returns the named behavior object. yiibaseComponent
getBehaviors() Returns all behaviors attached to this component. yiibaseComponent
handleError() Handles PHP execution errors such as warnings and notices. yiibaseErrorHandler
handleException() Handles uncaught PHP exceptions. yiibaseErrorHandler
handleFatalError() Handles fatal PHP errors. yiibaseErrorHandler
handleHhvmError() Handles HHVM execution errors such as warnings and notices. yiibaseErrorHandler
hasEventHandlers() Returns a value indicating whether there is any handler attached to the named event. yiibaseComponent
hasMethod() Returns a value indicating whether a method is defined. yiibaseComponent
hasProperty() Returns a value indicating whether a property is defined for this component. yiibaseComponent
init() yiibaseErrorHandler
logException() Logs the given exception. yiibaseErrorHandler
off() Detaches an existing event handler from this component. yiibaseComponent
on() Attaches an event handler to an event. yiibaseComponent
register() Register this error handler. yiibaseErrorHandler
trigger() Triggers an event. yiibaseComponent
unregister() Unregisters this error handler by restoring the PHP error and exception handlers. yiibaseErrorHandler

Protected Methods

Method Description Defined By
handleFallbackExceptionMessage() Handles exception thrown during exception processing in handleException(). yiibaseErrorHandler
renderException() Renders the exception. yiibaseErrorHandler

Events

Event Type Description Defined By
EVENT_SHUTDOWN yiibaseEvent An event that is triggered when the handler is called by shutdown function via handleFatalError(). (available since version 2.0.46) yiibaseErrorHandler

Property Details

Whether to discard any existing page output before error display. Defaults to true.

The exception that is being handled currently.

The size of the reserved memory. A portion of memory is pre-allocated so that when an out-of-memory issue occurs, the error handler is able to handle the error with the help of this reserved memory. If you set this value to be 0, no memory will be reserved. Defaults to 256KB.

If true — handleException() will finish script with ExitCode::OK . false — ExitCode::UNSPECIFIED_ERROR .

Источник

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

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

  • Yii2 error log
  • Yii2 error level
  • Yii2 error could not find driver
  • Yii2 captcha error
  • Yii2 api error handler

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

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