第一步,改配置
更改相应模块下(全局改application)config下的app.php,把改成自己的处理异常类
// 异常处理handle类 留空使用 \think\exception\Handle
'exception_handle' => '\app\lib\exception\MyExceptionHandler',
第二步,重写父类方法
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errorCode;
public function render(Exception $e)
{
if ($e instanceof BaseException)
{
//如果是自定义异常,则控制http状态码,不需要记录日志
//因为这些通常是因为客户端传递参数错误或者是用户请求造成的异常
//不应当记录日志
$this->code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
}
else{
// 如果是服务器未处理的异常,将http状态码设置为500,并记录日志
if(config('app_debug')){
// 调试状态下需要显示TP默认的异常页面,因为TP的默认页面
// 很容易看出问题
return parent::render($e);
}
$this->code = 500;
$this->msg = 'sorry,we make a mistake. (^o^)Y';
$this->errorCode = 999;
$this->recordErrorLog($e);
}
$request = request();
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request_url' => $request = $request->url()
];
return json($result, $this->code);
}
/*
* 将异常写入日志
*/
private function recordErrorLog(Exception $e)
{
Log::record($e->getMessage(),'error');
}
}
第三步,写异常类
class MissException extends BaseException
{
public $code = 404;
public $msg = 'global:your required resource are not found';
public $errorCode = 10001;
/**
* 构造函数,接收一个关联数组
* @param array $params 关联数组只应包含code、msg和errorCode,且不应该是空值
*/
public function __construct($params=[])
{
if(!is_array($params)){
return;
}
if(array_key_exists('code',$params)){
$this->code = $params['code'];
}
if(array_key_exists('msg',$params)){
$this->msg = $params['msg'];
}
if(array_key_exists('errorCode',$params)){
$this->errorCode = $params['errorCode'];
}
}
}
第四步,抛异常
if (!$banner ) {
throw new MissException([
'msg' => '请求banner不存在',
'errorCode' => 40000
]);
}