{
"code": 400,
"msg": "自定义异常信息",
"error_code": 10000,
"request": "/userapi/v1/[email protected]"
}
①:
// 异常处理handle类 留空使用 \think\exception\Handle【注意路径】
'exception_handle' => '\\app\\common\\exception\\ExceptionHandle',
自定义类需要继承think\exception\Handle并且实现render方法
【BaseException】异常基类
code = $params['code'];
}
if(array_key_exists('msg',$params)){
$this->msg = $params['msg'];
}
if(array_key_exists('errorCode',$params)){
$this->errorCode = $params['errorCode'];
}
}
}
【ExceptionHandle】
code = $e->code;
$this->msg = $e->msg;
$this->errorCode = $e->errorCode;
} else {
if (Config::get('app_debug')) {
// 如果当前开启bug调试时,则不做处理,因为会显示比较全的提示错误
return parent::render($e);
}
$this->code = 500;
$this->mas = 'error';
$this->errorCode = '999';
// 写入日志
$this->recordErrorLog($e);
}
$request = \think\facade\Request::instance();
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request' => $request->url(),
];
return json($result,$this->code);
}
/**
* 将异常写入日志
* @param $e
*/
protected function recordErrorLog($e)
{
// 写入日志操作
// Log::init([
// 'type' => 'File',
// 'path' => LOG_PATH,
// 'level' => ['error']
// ]);
// Log::record($e->getTraceAsString());
Log::record($e->getMessage(),'error');
}
}
-------------------------------
【ParamBaseException】参数异常
msg = $msg;
}
}
Tp5自定义日志文件:
// 独立日志级别
'apart_level' => [
'demo'
],
Log::record('aaaaaaaabbbbbbbbbbbbbbbbbbaaaaaaaa','demo');
private function setHeader()
{
// 公共响应头
header('Content-Type: Application/json');
// 如果需要跨域,写在这里
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: x-token,user-type,Origin,Access-Control-Request-Headers,SERVER_NAME,Access-Control-Allow-Headers,cache-control,token, X-Requested-With,Content-Type,Accept,Connection,User-Agent,Cookie');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
// 如果是options请求,直接响应
if (request()->method() == 'OPTIONS') {
return '';
}
}
````