🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 异常处理 >本着严谨的原则,框架会对任何错误(包括警告错误)抛出异常。系统产生的异常和错误都是程序的隐患,要尽早排除和解决,而不是掩盖。对于应用自己抛出的异常则做出相应的捕获处理。 不同模块处理调用相对异常处理类,详情见【CRMEB类库】->【Exceptions错误抛出】 可以整体所有应用定义统一异常处理类,`app`下或单独应用`api`下`provider.php`注入绑定异常处理类 api应用下: ``` // 容器Provider定义文件 return [ 'think\exception\Handle' => \app\api\ApiExceptionHandle::class, ]; ``` 自定义类需要继承`think\exception\Handle`并且实现`render`方法 如下完成类: ~~~ <?php namespace app\api; use crmeb\exceptions\ApiException; use crmeb\exceptions\AuthException; use think\exception\DbException; use think\exception\Handle; use think\facade\Env; use think\Response; use Throwable; use think\exception\ValidateException; class ApiExceptionHandle extends Handle { /** * 记录异常信息(包括日志或者其它方式记录) * * @access public * @param Throwable $exception * @return void */ public function report(Throwable $exception): void { // 使用内置的方式记录异常日志 parent::report($exception); } /** * Render an exception into an HTTP response. * * @access public * @param \think\Request $request * @param Throwable $e * @return Response */ public function render($request, Throwable $e): Response { // 添加自定义异常处理机制 if ($e instanceof DbException) { return app('json')->fail('数据获取失败', [ 'file' => $e->getFile(), 'message' => $e->getMessage(), 'line' => $e->getLine(), ]); } else if ($e instanceof AuthException || $e instanceof ApiException || $e instanceof ValidateException) { return app('json')->fail($e->getMessage()); } else { return app('json')->fail('很抱歉!系统开小差了', Env::get('app_debug', false) ? [ 'message' => $e->getMessage(), 'file' => $e->getFile(), 'code' => $e->getCode(), 'line' => $e->getLine(), 'trace' => $e->getTrace(), 'previous' => $e->getPrevious(), ] : []); } } } ~~~ ### 手动捕获抛和出异常 可以手动使用`throw`来抛出一个异常 ``` // 使用think自带异常类抛出异常 throw new \\think\\Exception('异常消息', 400); ``` 手动捕获异常方式是使用`try-catch` ``` try { // 这里是主体代码 } catch (ValidateException $e) { // 这是进行验证异常捕获 return json($e->getError()); } catch (\Exception $e) { // 这是进行异常捕获 return json($e->getMessage()); } ```