You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

144 lines
4.8 KiB

<?php
declare(strict_types=1);
/**
* ExceptionHandle.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app;
use app\middleware\Trace;
use app\service\score\exception\UnsupportedStrategyException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\facade\Log;
use think\response\Json;
use Throwable;
/**
* 全局异常渲染
* 设计说明:
* - 任何异常都必须变成 code/msg/data 统一响应体
* 不允许框架默认的 HTML 错误页漏给小程序:小程序拿到 HTML 会解析失败,用户看到白屏
* - 状态码只取 400 / 500 两种(规范第七节),细分原因放 data.err_code
* 前端优先用 err_code 分支,msg 只用于文案展示
* 若只能匹配中文文案来分支,改一次文案就会静默失效
* - trace_id 不进响应体(规范固定为 code/msg/data),只保留响应头 X-Trace-Id
*/
class ExceptionHandle extends Handle
{
/**
* 不记录日志的异常类型
*
* 这一段来自官方骨架,必须保留。
* 删掉的后果:404 / 405 / 参数校验失败这类「客户端问题」会全部写进日志,
* 日志被刷满,真正需要关注的 500 反而被埋掉。
* 它们仍然会被正常渲染成统一响应体(render 里会处理),不记日志不影响用户。
*
* 早期版本重写本文件时漏了这一属性,属于「看起来只是少一段注释」的隐性回退。
*
* @var array
*/
protected $ignoreReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
DataNotFoundException::class,
ValidateException::class,
];
/**
* 渲染异常
* render
* @param \think\Request $request 请求对象
* @param Throwable $e 异常
* @return Json
*/
public function render($request, Throwable $e): \think\Response
{
// 策略注册表错误属于配置问题,按系统错误处理而不是业务失败
if ($e instanceof UnsupportedStrategyException) {
Log::error('[score] ' . $e->getMessage());
return $this->fail(config('code.error'), $e->getMessage(), config('code.err.score_failed'));
}
if ($e instanceof BusinessException) {
return $this->fail(config('code.fail'), $e->getMessage(), $e->getErrCode());
}
if ($e instanceof ValidateException) {
return $this->fail(config('code.fail'), $e->getMessage(), config('code.err.param'));
}
if ($e instanceof HttpException) {
$status_code = $e->getStatusCode();
$msg = '请求的接口不存在';
$err_code = config('code.err.not_found');
if ($status_code === 405) {
$msg = '请求方式不被允许';
$err_code = config('code.err.method_not_allow');
}
if ($status_code === 403) {
$msg = '无权限访问';
$err_code = config('code.err.forbidden');
}
return $this->fail(config('code.fail'), $msg, $err_code);
}
if ($e instanceof DataNotFoundException || $e instanceof ModelNotFoundException) {
return $this->fail(config('code.fail'), '请求的资源不存在', config('code.err.not_found'));
}
// 兜底:记日志后返回系统错误;调试模式下附上原始信息便于定位
Log::error('[uncaught] ' . $e::class . ': ' . $e->getMessage(), [
'file' => $e->getFile() . ':' . $e->getLine(),
'trace' => $e->getTraceAsString(),
'trace_id' => Trace::traceId()
]);
$debug_data = [];
if (app()->isDebug()) {
$debug_data['exception'] = $e::class;
$debug_data['file'] = $e->getFile() . ':' . $e->getLine();
}
return $this->fail(config('code.error'), '系统繁忙,请稍后再试', config('code.err.server_busy'), $debug_data);
}
/**
* 组装失败响应
* fail
* @param int $code 状态码
* @param string $msg 中文原因
* @param mixed $err_code 细分业务码
* @param array $extra 额外明细
* @return Json
*/
private function fail($code, $msg, $err_code, $extra = [])
{
$data = [];
$data['err_code'] = $err_code;
foreach ($extra as $key => $value) {
$data[$key] = $value;
}
return json([
'code' => $code,
'msg' => $msg,
'data' => $data
], 200)->header(['X-Trace-Id' => Trace::traceId()]);
}
}