# 異常處理
路由如果沒有匹配到任何頁面,會調用配置 error_controller_name 指定的異常處理類,默認為GoController::class。
~~~
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個時機。
>[info] 如果異常發生時,代碼沒有執行到控制器里比如404,405,則會調用GoController::onExceptionHandle 的方法進行處理。也就是 error_controller_name 配置的異常處理類。該類需要繼承 GoController 。
>[warning] 如果異常發生時,已經執行到控制器里,比如自己throw了一個異常,會優先調用該控制器里的onExceptionHandle 方法。
如果需要自定義錯誤處理,請注意異常發生的時機。
# 自定義處理異常案例
~~~
<?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請求會返回。
~~~
{
"code": 23333,
"msg": "aaa",
"data": null
}
~~~
## AlertResponseException
該異常會捕獲并返回 http500 , 內部服務器錯誤,日志會記錄詳細的錯誤信息,用于系統出現問題的時候調用。
~~~
錯誤消息
內部服務器錯誤,請稍后再試
~~~
如果是ajax請求會返回
~~~
{
"code": 500,
"msg": "內部服務器錯誤,請稍后再試",
"data": null
}
~~~
- 前言
- 捐贈ESD項目
- 使用篇-通用
- 環境
- 安裝
- 規范
- 壓力測試
- 配置
- 如何設置YML配置
- server配置
- 端口配置
- 項目結構
- 事件派發
- 日志
- 注解
- DI容器
- 自定義進程
- 并發及協程池
- Console插件
- Scheduled插件
- Redis插件
- AOP插件
- Saber插件
- Mysql插件
- mysql事務
- Actuator插件
- Whoops插件
- Cache插件
- PHPUnit插件
- Security插件
- Session插件
- EasyRoute插件
- http路由
- ProcessRpc插件
- AutoReload插件
- AnnotationsScan插件
- Tracing-plugin插件
- MQTT插件
- Pack插件
- AMQP插件
- Validate插件
- Uid插件
- Topic插件
- Blade插件
- CsvReader插件
- hashed-wheel-timer-plugin插件
- 使用篇-HTTP
- 路由
- 靜態文件
- 路由定義
- 修飾方法
- 路由分組
- 資源路由
- 端口作用域
- 異常處理
- 跨域請求
- 路由緩存
- 控制器
- 控制器初始化
- 前置操作
- 跳轉和重定向
- 異常處理
- 請求
- 請求對象
- 請求信息
- request消息
- response消息
- stream消息
- url接口
- 驗證器
- 內置驗證器
- 內置過濾器
- 使用篇-WS
- 如何使用
- 路由
- 使用篇-TCP
- 插件篇-PluginSystem
- 微服務篇-ESDCloud
- CircuitBreaker插件
- SaberCloud插件
- 分布式鏈路追蹤系統
- Consul插件