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()]); } }