123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace app\api\library;
- use Exception;
- use think\exception\Handle;
- use think\Log;
- use app\common\exception\BusinessException;
- /**
- * 自定义API模块的错误显示
- * 统一处理API异常和服务层异常
- */
- class ExceptionHandle extends Handle
- {
-
- public function render(Exception $e)
- {
- // 业务异常:开发和生产环境都返回json
- if ($e instanceof BusinessException) {
- $code = 0;
- $statuscode = 200;
- $msg = $e->getMessage() ?: '业务处理失败';
- Log::record([
- 'exception' => 'BusinessException',
- 'custom_error_code' => $e->getErrorCode(),
- 'message' => $e->getMessage(),
- 'error_data' => $e->getErrorData(),
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- ], 'info');
- return json([
- 'code' => $code,
- 'msg' => $msg,
- 'time' => time(),
- 'data' => null
- ], $statuscode);
- }
- // 在生产环境下返回code信息
- if (!\think\Config::get('app_debug')) {
- $statuscode = $code = 500;
- $msg = 'An error occurred';
-
- // 验证异常
- if ($e instanceof \think\exception\ValidateException) {
- $code = 0;
- $statuscode = 200;
- $msg = $e->getError();
- }
- // Http异常
- elseif ($e instanceof \think\exception\HttpException) {
- $statuscode = $code = $e->getStatusCode();
- $msg = $e->getMessage() ?: 'Http Error';
- }
- // 自定义业务异常(与验证异常保持一致的返回格式)
- elseif ($e instanceof BusinessException) {
- $code = 0; // 业务异常统一返回code=0,与验证异常一致
- $statuscode = 200; // HTTP状态码为200
- $msg = $e->getMessage() ?: '业务处理失败';
-
- // 记录业务异常日志(便于调试,包含自定义错误码)
- Log::record([
- 'exception' => 'BusinessException',
- 'custom_error_code' => $e->getErrorCode(), // 记录自定义错误码用于调试
- 'message' => $e->getMessage(),
- 'error_data' => $e->getErrorData(),
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- ], 'info'); // 业务异常用info级别记录
- }
- // 其他异常(包括服务层的普通Exception)
- elseif ($e instanceof \Exception) {
- $code = 0; // 普通异常统一返回code=0
- $statuscode = 200; // HTTP状态码为200
- $msg = $e->getMessage() ?: '业务处理失败';
-
- // 记录服务层异常日志(便于调试)
- Log::record([
- 'exception' => get_class($e),
- 'message' => $e->getMessage(),
- 'file' => $e->getFile(),
- 'line' => $e->getLine(),
- 'trace' => $e->getTraceAsString()
- ], 'error');
- }
-
- return json([
- 'code' => $code,
- 'msg' => $msg,
- 'time' => time(),
- 'data' => null
- ], $statuscode);
- }
- // 开发环境下交由系统处理
- return parent::render($e);
- }
- }
|