易优CMS异常处理 |
和PHP默认的异常处理不同,ThinkPHP抛出的不是单纯的错误信息,而是一个人性化的错误页面。 默认异常处理在调试模式下,系统默认展示的错误页面:
// 异常错误报错级别,error_reporting(E_ERROR | E_PARSE ); 异常处理接管
框架支持异常页面由开发者自定义类进行处理,需要配置参数 // 异常处理handle类 留空使用 \think\exception\Handle 'exception_handle' => '\\app\\common\\exception\\Http',
自定义类需要继承 <?phpnamespace app\common\exception;use Exception;use think\exception\Handle;use think\exception\HttpException;class Http extends Handle{ public function render(Exception $e) { // 参数验证错误 if ($e instanceof ValidateException) { return json($e->getError(), 422); } // 请求异常 if ($e instanceof HttpException && request()->isAjax()) { return response($e->getMessage(), $e->getStatusCode()); } //TODO::开发者对异常的操作 //可以在此交由系统处理 return parent::render($e); }}
'exception_handle' => function(Exception $e){ // 参数验证错误 if ($e instanceof \think\exception\ValidateException) { return json($e->getError(), 422); } // 请求异常 if ($e instanceof \think\exception\HttpException && request()->isAjax()) { return response($e->getMessage(), $e->getStatusCode()); }} 部署模式异常一旦关闭调试模式,发生错误后不会提示具体的错误信息,如果你仍然希望看到具体的错误信息,那么可以如下设置: // 显示错误信息'show_error_msg' => true,
异常捕获
可以使用PHP的异常捕获进行必要的处理,但需要注意一点,在异常捕获中不要使用 try{ Db::name('user')->find(); $this->success('执行成功!');}catch(\Exception $e){ $this->error('执行错误');} 应该改成 try{ Db::name('user')->find();}catch(\Exception $e){ $this->error('执行错误');}$this->success('执行成功!'); |