全局异常处理类
# 用于自定义全局异常处理
use think\exception\Handle;
use think\Log;
use think\Request;
use Exception;
class ExceptionHandler extends Handle
{
private $code;
private $msg;
private $errorCode;
/**
* @param Exception $e
* @return \think\Response|\think\response\Json
*/
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::instance();
$result = [
'msg' => $this->msg,
'error_code' => $this->errorCode,
'request_url' => $request = $request->url()
];
return json($result, $this->code);
}
/*
* 将异常写入日志
*/
private function recordErrorLog(Exception $e)
{
Log::init([
'type' => 'File',
'path' => LOG_PATH,
'level' => ['error']
]);
Log::record($e->getMessage(),'error');
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 基础自定义异常类
use think\Exception;
class BaseException extends Exception
{
// HTTP 状态码
public $code = 400;
// 错误具体信息
public $msg = '参数错误'; // 最好初始化为英文格式的
// 自定义的错误码
public $errorCode = 10000;
/**
* BaseException constructor.
* @param array $params
* @throws Exception
*/
public function __construct($params = [])
{
if (!is_array($params)) {
throw new Exception('参数必须是数组');
}
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'];
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
以后别的异常类都可以进行继承此父类
编辑 (opens new window)
上次更新: 2021/10/21, 20:43:49