自定义异常处理类
> TP5 的 config.php 文件中可以自定义异常处理类
![](https://box.kancloud.cn/28a7d62e140a20a92cb8289d98578f74_880x101.png)
代码如下:
~~~
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');
}
}
~~~