全局異常處理handler
~~~
public function render(\Exception $e)
{
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);
~~~
自定義異常類
~~~
class BaseException extends Exception
{
//HTTP 狀態碼 404,200
public $code=400;
//錯誤具體信息
public $msg="自定義錯誤";
//自定義的錯誤碼
public $errCode=10000;
//構造函數初始化類屬性
public function __construct(array $conf=[])
{
//防御性代碼
if(!is_array($conf)) return;
//屬性初始化
array_key_exists('msg',$conf)&&$this->msg=$conf['msg'];
array_key_exists('errCode',$conf)&&$this->errCode=$conf['errCode'];
array_key_exists('code',$conf)&&$this->url=$conf['code'];
}
}
~~~