Yii錯誤異常處理


背景

當程序中出現不可預期的錯誤,比如說除0異常,yii會給我們扔出這個異常信息,由於現在都是讀寫分離,客戶端調你的api,都是協商好的數據格式,如果業務方沒有兼容你的異常返回,客戶端出現異常錯誤,影響也挺惡心。

再者,寫些腳本的時候,出現不可預期的異常沒有記到日志中,對於我們排查錯誤也是大大的麻煩。好在,yii提供錯誤處理,看看官方文檔:錯誤處理

默認的錯誤處理是 (web)https://www.yiichina.com/doc/api/2.0/yii-web-errorhandler (console)https://www.yiichina.com/doc/api/2.0/yii-console-errorhandler,
通過重寫renderException方法,就可以達到自定義的錯誤輸出。

web錯誤處理

web.php 配置:

...
 'errorHandler' => [
            'class' => 'app\controllers\ErrorController',
            'errorAction' => 'site/error',
        ],
...

ErrorController.php

<?php

namespace app\controllers;

use app\modules\Common;
use Yii;


class ErrorController extends \yii\web\ErrorHandler{

    protected function renderException($exception){

        //todo 業務處理異常
        //if( Yii::$app->request->getIsPost() && !Yii::$app->request->get('fullerror')){
        //    return Common::echoJson(500, $exception->getMessage());
        //}

        parent::renderException($exception);
    }

}

console錯誤處理

console.php

...
   'errorHandler' => [
            'class' => 'app\commands\ErrorController'
        ],

ErrorController.php

<?php
namespace app\commands;

use Yii;
use yii\helpers\FileHelper;
use yii\log\FileTarget;
use yii\log\Logger;


class ErrorController extends \yii\base\ErrorHandler{

    protected function renderException($exception){

        //業務處理異常
        $errMsg = "文件位置:{$exception->getFile()} 所在行:{$exception->getLine()}\n". "錯誤:".$exception->getMessage();
        self::writeLog('sys_exception.log',date('Y-m-d H:i:s') . "{$errMsg}\n");
    }


    public static function writeLog($fileName, $message,$categories='')
    {
        $logPath = Yii::$app->getRuntimePath() . '/logs/' . date("Ymd") . "/";
        FileHelper::createDirectory($logPath);
        $file = new FileTarget();
        $file->logFile = $logPath . $fileName;
        $file->messages[] = [$message, Logger::LEVEL_INFO, $categories, time()];
        $file->export();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM