自定義異常處理類
> TP5 的 config.php 文件中可以自定義異常處理類

代碼如下:
~~~
use think\exception\Handle;
use think\Log;
use think\Request;
// 通過重寫框架的 Handle 來實現自定義異常
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errCode;
public function render(\Exception $e) {
if ($e instanceof BaseException) {
$this->code = $e->code;
$this->msg = $e->msg;
$this->errCode = $e->errCode;
} else {
if (config('app_debug')) {
// 調試模式使用框架 render,方便開發
return parent::render($e);
} else {
$this->code = 500;
$this->msg = '服務器內部錯誤';
$this->errCode = 999;
// 寫入日志
$this->recordErrorLog($e);
}
}
$request = Request::instance();
$result = [
'msg' => $this->msg,
'errCode' => $this->errCode,
'request_url' => $request->url()
];
return json($result, $this->code);
}
/**
* 記錄日志
* @param \Exception $e
*/
private function recordErrorLog(\Exception $e) {
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error']
]);
Log::record($e->getMessage(), 'error');
}
}
~~~