From 0afc7b1bbf31ef21866ecc2cc02218dfaf284364 Mon Sep 17 00:00:00 2001 From: xiongxiaoyang <1179705413@qq.com> Date: Tue, 18 Mar 2025 21:03:21 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=80=9A=E7=94=A8=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../core/advice/CommonExceptionHandler.java | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/novel-common/src/main/java/com/java2nb/novel/core/advice/CommonExceptionHandler.java b/novel-common/src/main/java/com/java2nb/novel/core/advice/CommonExceptionHandler.java index 16509b1..cae9f25 100644 --- a/novel-common/src/main/java/com/java2nb/novel/core/advice/CommonExceptionHandler.java +++ b/novel-common/src/main/java/com/java2nb/novel/core/advice/CommonExceptionHandler.java @@ -3,11 +3,19 @@ package com.java2nb.novel.core.advice; import io.github.xxyopen.model.resp.RestResult; import io.github.xxyopen.model.resp.SysResultCode; import io.github.xxyopen.web.exception.BusinessException; +import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.MediaType; import org.springframework.validation.BindException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.servlet.ModelAndView; +/** + * 统一异常处理器 + * + * @author xiongxiaoyang + */ @Slf4j @RestControllerAdvice public class CommonExceptionHandler { @@ -27,9 +35,21 @@ public class CommonExceptionHandler { return RestResult.fail(e.getResultCode()); } - @ExceptionHandler({Exception.class}) - public RestResult handlerException(Exception e) { + @ExceptionHandler(Exception.class) + public Object handleException(HttpServletRequest request, Exception e) { log.error(e.getMessage(), e); - return RestResult.error(); + if (isJsonRequest(request)) { + // 如果是REST请求,返回JSON格式的错误响应 + return RestResult.error(); + } else { + //跳转页面过程中出现异常时统一跳转到404页面 + return new ModelAndView("404"); + } } + + private boolean isJsonRequest(HttpServletRequest request) { + String acceptHeader = request.getHeader("Accept"); + return acceptHeader != null && acceptHeader.contains(MediaType.APPLICATION_JSON_VALUE); + } + } \ No newline at end of file