How do you implement a custom error handler in Yii?

How do you implement a custom error handler in Yii?

Implementing a custom error handler in Yii allows you to manage how errors and exceptions are displayed or logged in your application. Here’s a concise guide to set up a custom error handler in Yii.

Minimal Steps to Implement a Custom Error Handler in Yii

Create a Custom Error Handler Class:

  • Create a new PHP file for your custom error handler (e.g., components/CustomErrorHandler.php).

Example: CustomErrorHandler.php

Example

<?php
namespace app\components;

use Yii;
use yii\web\HttpException;
use yii\web\ErrorHandler;

class CustomErrorHandler extends ErrorHandler
{
    protected function renderException($exception)
    {
        // Customize the response for different types of exceptions
        if ($exception instanceof HttpException) {
            Yii::$app->response->statusCode = $exception->statusCode;
            return $this->renderAjaxError($exception); // Optionally, customize for AJAX
        }

        // Default error response
        Yii::$app->response->statusCode = 500;
        return $this->renderErrorPage($exception);
    }

    protected function renderErrorPage($exception)
    {
        // Render your custom error view
        return $this->renderFile('@app/views/site/error.php', ['exception' => $exception]);
    }
}
?>

Register the Custom Error Handler in Configuration:

  • Open your config/web.php file and replace the default error handler with your custom one.

Example

<?php
'components' => [
    'errorHandler' => [
        'class' => 'app\components\CustomErrorHandler',
        'errorAction' => 'site/error', // Optional: Redirect to a specific action
    ],
],
?>

Create an Error View:

  • Create a view file (e.g., views/site/error.php) to display error messages.

Example: error.php

Example

<?php
<?php
use yii\helpers\Html;

$this->title = 'Error';
?>
<div class="site-error">
    <h1><?= Html::encode($this->title) ?></h1>
    <div class="alert alert-danger">
        <p><?= nl2br(Html::encode($exception->getMessage())) ?></p>
    </div>
</div>
?>

Test Your Custom Error Handler:

  • Trigger an error (e.g., by accessing a nonexistent route) to see if your custom error handling works.

Related Questions & Topics

Powered and designed by igetvapeaustore.com | © 2024 codestap.com.