chengkun
2025-09-15 0cc7f61de2b106c9664033fc27d6426d072ea019
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2025 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);
 
namespace think\exception;
 
use Exception;
use think\App;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;
use Throwable;
 
/**
 * 系统异常处理类
 */
class Handle
{
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];
 
    protected $showErrorMsg = [
 
    ];
 
    public function __construct(protected App $app)
    {
    }
 
    /**
     * Report or log an exception.
     *
     * @access public
     * @param Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        if (!$this->isIgnoreReport($exception)) {
            // 收集异常数据
            if ($this->app->isDebug()) {
                $data = [
                    'file'    => $exception->getFile(),
                    'line'    => $exception->getLine(),
                    'message' => $this->getMessage($exception),
                    'code'    => $this->getCode($exception),
                ];
                $log  = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";
            } else {
                $data = [
                    'code'    => $this->getCode($exception),
                    'message' => $this->getMessage($exception),
                ];
                $log  = "[{$data['code']}]{$data['message']}";
            }
 
            if ($this->app->config->get('log.record_trace')) {
                $log .= PHP_EOL . $exception->getTraceAsString();
            }
 
            try {
                $this->app->log->record($log, 'error');
            } catch (Exception $e) {
            }
        }
    }
 
    protected function isIgnoreReport(Throwable $exception): bool
    {
        foreach ($this->ignoreReport as $class) {
            if ($exception instanceof $class) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render(Request $request, Throwable $e): Response
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof HttpException) {
            return $this->renderHttpException($request, $e);
        } else {
            return $this->convertExceptionToResponse($request, $e);
        }
    }
 
    /**
     * @access public
     * @param Output    $output
     * @param Throwable $e
     */
    public function renderForConsole(Output $output, Throwable $e): void
    {
        if ($this->app->isDebug()) {
            $output->setVerbosity(Output::VERBOSITY_DEBUG);
        }
 
        $output->renderException($e);
    }
 
    /**
     * @access protected
     * @param HttpException $e
     * @return Response
     */
    protected function renderHttpException(Request $request, HttpException $e): Response
    {
        $status   = $e->getStatusCode();
        $template = $this->app->config->get('app.http_exception_template');
 
        if (!$this->app->isDebug() && !empty($template[$status])) {
            return Response::create($template[$status], 'view', $status)->assign(['e' => $e]);
        } else {
            return $this->convertExceptionToResponse($request, $e);
        }
    }
 
    /**
     * 收集异常数据
     * @param Throwable $exception
     * @return array
     */
    protected function convertExceptionToArray(Throwable $exception): array
    {
        return $this->app->isDebug() ? $this->getDebugMsg($exception) : $this->getDeployMsg($exception);
    }
 
    /**
     * 是否显示错误信息
     * @param \Throwable $exception
     * @return bool
     */
    protected function isShowErrorMsg(Throwable $exception)
    {
        foreach ($this->showErrorMsg as $class) {
            if ($exception instanceof $class) {
                return true;
            }
        }
 
        return false;
    }
 
    /**
     * 获取部署模式异常数据
     * @access protected
     * @param Throwable $exception
     * @return array
     */
    protected function getDeployMsg(Throwable $exception): array
    {
        $showErrorMsg = $this->isShowErrorMsg($exception);
        if ($showErrorMsg || $this->app->config->get('app.show_error_msg', false)) {
            $message = $this->getMessage($exception);
        } else {
            // 不显示详细错误信息
            $message = $this->app->config->get('app.error_message');
        }
 
        return [
            'code'    => $this->getCode($exception),
            'message' => $message,
        ];
    }
 
    /**
     * 收集调试模式异常数据
     * @access protected
     * @param Throwable $exception
     * @return array
     */
    protected function getDebugMsg(Throwable $exception): array
    {
        // 调试模式,获取详细的错误信息
        $traces        = [];
        $nextException = $exception;
 
        do {
            $traces[] = [
                'name'    => $nextException::class,
                'file'    => $nextException->getFile(),
                'line'    => $nextException->getLine(),
                'code'    => $this->getCode($nextException),
                'message' => $this->getMessage($nextException),
                'trace'   => $nextException->getTrace(),
                'source'  => $this->getSourceCode($nextException),
            ];
        } while ($nextException = $nextException->getPrevious());
 
        return [
            'code'    => $this->getCode($exception),
            'message' => $this->getMessage($exception),
            'traces'  => $traces,
            'datas'   => $this->getExtendData($exception),
            'tables'  => [
                'GET Data'            => $this->app->request->get(),
                'POST Data'           => $this->app->request->post(),
                'Files'               => $this->app->request->file(),
                'Cookies'             => $this->app->request->cookie(),
                'Session'             => $this->app->exists('session') ? $this->app->session->all() : [],
                'Server/Request Data' => $this->app->request->server(),
            ],
        ];
    }
 
    protected function isJson(Request $request, Throwable $exception)
    {
        return $request->isJson();
    }
 
    /**
     * @access protected
     * @param Throwable $exception
     * @return Response
     */
    protected function convertExceptionToResponse(Request $request, Throwable $exception): Response
    {
        if ($this->isJson($request, $exception)) {
            $response = Response::create($this->convertExceptionToArray($exception), 'json');
        } else {
            $response = Response::create($this->renderExceptionContent($exception));
        }
 
        if ($exception instanceof HttpException) {
            $statusCode = $exception->getStatusCode();
            $response->header($exception->getHeaders());
        }
 
        return $response->code($statusCode ?? 500);
    }
 
    protected function renderExceptionContent(Throwable $exception): string
    {
        ob_start();
        $data = $this->convertExceptionToArray($exception);
        extract($data);
        include $this->app->config->get('app.exception_tmpl') ?: __DIR__ . '/../../tpl/think_exception.tpl';
 
        return ob_get_clean();
    }
 
    /**
     * 获取错误编码
     * ErrorException则使用错误级别作为错误编码
     * @access protected
     * @param Throwable $exception
     * @return integer                错误编码
     */
    protected function getCode(Throwable $exception)
    {
        $code = $exception->getCode();
 
        if (!$code && $exception instanceof ErrorException) {
            $code = $exception->getSeverity();
        }
 
        return $code;
    }
 
    /**
     * 获取错误信息
     * ErrorException则使用错误级别作为错误编码
     * @access protected
     * @param Throwable $exception
     * @return string                错误信息
     */
    protected function getMessage(Throwable $exception): string
    {
        $message = $exception->getMessage();
 
        if ($this->app->runningInConsole()) {
            return $message;
        }
 
        $lang = $this->app->lang;
 
        if (str_contains($message, ':')) {
            $name    = strstr($message, ':', true);
            $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message;
        } elseif (str_contains($message, ',')) {
            $name    = strstr($message, ',', true);
            $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message;
        } elseif ($lang->has($message)) {
            $message = $lang->get($message);
        }
 
        return $message;
    }
 
    /**
     * 获取出错文件内容
     * 获取错误的前9行和后9行
     * @access protected
     * @param Throwable $exception
     * @return array                 错误文件内容
     */
    protected function getSourceCode(Throwable $exception): array
    {
        // 读取前9行和后9行
        $line  = $exception->getLine();
        $first = ($line - 9 > 0) ? $line - 9 : 1;
 
        try {
            $contents = file($exception->getFile()) ?: [];
            $source   = [
                'first'  => $first,
                'source' => array_slice($contents, $first - 1, 19),
            ];
        } catch (Exception $e) {
            $source = [];
        }
 
        return $source;
    }
 
    /**
     * 获取异常扩展信息
     * 用于非调试模式html返回类型显示
     * @access protected
     * @param Throwable $exception
     * @return array                 异常类定义的扩展数据
     */
    protected function getExtendData(Throwable $exception): array
    {
        $data = [];
 
        if ($exception instanceof \think\Exception) {
            $data = $exception->getData();
        }
 
        return $data;
    }
 
    /**
     * 获取常量列表
     * @access protected
     * @return array 常量列表
     */
    protected function getConst(): array
    {
        $const = get_defined_constants(true);
 
        return $const['user'] ?? [];
    }
}