多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 异常处理 此页面参照了EasySwoole Distributed的文档,原文档地址 [https://www.kancloud.cn/tmtbe/goswoole/1086151]: https://www.kancloud.cn/tmtbe/goswoole/1086151 路由如果没有匹配到任何页面,会调用配置 error_controller_name 指定的异常处理类,默认为GoController::class。 ```php public function onExceptionHandle(\Throwable $e) { if ($this->whoopsConfig->isEnable() && Server::$instance->getServerConfig()->isDebug()) { throw $e; } if ($this->clientData->getResponse() != null) { $this->response->withStatus(404); $this->response->withHeader("Content-Type", "text/html;charset=UTF-8"); if($e instanceof RouteException) { $msg = '404 Not found / ' . $e->getMessage(); return $msg; }else if ($e instanceof AccessDeniedException) { $this->response->withStatus(401); $msg = '401 Access denied / ' . $e->getMessage(); return $msg; }else if($e instanceof ResponseException){ $this->response->withStatus(200); return $this->errorResponse($e->getMessage(), $e->getCode()); }else if ($e instanceof AlertResponseException){ $this->response->withStatus(500); return $this->errorResponse($e->getMessage(), $e->getCode()); } } return parent::onExceptionHandle($e); } ``` ## 自定义异常处理 自定义异常处理,有2个时机。 > 如果异常发生时,代码没有执行到控制器里比如404,405,则会调用GoController::onExceptionHandle 的方法进行处理。也就是 error_controller_name 配置的异常处理类。该类需要继承 GoController 。 > 如果异常发生时,已经执行到控制器里,比如自己throw了一个异常,会优先调用该控制器里的onExceptionHandle 方法。 如果需要自定义错误处理,请注意异常发生的时机。 ## 自定义处理异常案例 ```php <?php /** * Created by PhpStorm. * User: anythink * Date: 2019/5/31 * Time: 6:26 PM */ namespace app\Controller; use ESD\Go\GoController; class ExceptionClass extends GoController{ function onExceptionHandle(\Throwable $e) { $this->response->withHeader("content-type",'text/html;charset=utf-8'); if($e instanceof \Exception){ return '拦截所有异常'; } return parent::onExceptionHandle($e); // TODO: Change the autogenerated stub } } ``` 配置文件 ``` route: error_controller_name: app\Controller\ExceptionClass ``` ## 框架提供的可用异常 该异常框架内部不会抛出,均由用户自行使用。 ## ResponseException 该异常会被捕获并返回message,code,如果不是ajax请求会返回。 ``` 错误消息 aaa ``` 如果是ajax请求会返回。 ```json { "code": 23333, "msg": "aaa", "data": null } ``` ## AlertResponseException 该异常会捕获并返回 http500 , 内部服务器错误,日志会记录详细的错误信息,用于系统出现问题的时候调用。 ``` 错误消息 内部服务器错误,请稍后再试 ``` 如果是ajax请求会返回 ```json { "code": 500, "msg": "内部服务器错误,请稍后再试", "data": null } ```