**一. 異常的分類:**
**1. 由于用戶行為導致的異常(沒有通過驗證器,沒查詢到結果)**
通常不需要記錄日志 需要向用戶返回具體信息
**2. 服務器自身異常(代碼錯誤, 調用外部接口錯誤)**
通常只記錄日志 不向客戶端返回具體原因
全局異常處理類[配置文件中指向該文件]
~~~
class ExceptionHandler extends Handle {
private $code;
private $msg;
private $errCode;
//需要返回客戶端當前請求的url路徑
/**
* @param Exception $e
* @return \think\Response|void
*/
public function render(\Exception $e)
{
// 自定義的異常類,繼承BaseException
if($e instanceof BaseException){
$this->code=$e->code;
$this->msg=$e->msg;
$this->errCode=$e->errCode;
}else{
// 系統的異常,判斷是不是調試模式:是,顯示tp5的異常,否則顯示封裝接口的異常
if(config('app.app_debug')){
//使用tp5默認的錯誤提示
return parent::render($e);
}else{
$this->code=500;
$this->msg='服務器內部錯誤';
$this->errCode=999;
//真是的錯誤寫入日志
// echo($e->getMessage());
Log::record($e->getMessage(),'error');
}
}
//返回錯誤數據
$url=request()->url();
$result=[
'msg'=>$this->msg,
'errCode'=>$this->errCode,
'url'=>$url
];
return json($result,$this->code);
}
}
~~~