有些時候我們不需要yii2框架輸出一大堆的html錯誤定位,只需要簡單的核心錯誤描述即可,這個時候需要繼承yii2框架的ErrorHandler類,重寫renderException方法即可。
<?php
namespace app\components;
use app\Utils\ResponseUtil;
use yii\helpers\Json;
class ErrorHandler extends \yii\base\ErrorHandler
{
/**
* Renders the exception.
* @param \Exception $exception the exception to be rendered.
*/
protected function renderException($exception)
{
$title = $exception->getMessage();
$message = $exception->getFile().":".$exception->getLine();
$code = $exception->getCode();
$data = [
'title' => $title,
'message' => $message,
'code' => $code
];
echo Json::encode(ResponseUtil::buildResponse(500,'服務器內部錯誤',$data));
\Yii::$app->end();
}
}
這裏是針對接口設定的錯誤格式,還可以直接跳轉一個錯誤頁面,
return $this->render('@app/views/site/error',['error'=>$exception]);
完畢。