SpringBoot配置全局的异常捕获 - 同时兼容web与ajax
    		       		warning:
    		            这篇文章距离上次修改已过445天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中,可以通过@ControllerAdvice和@ExceptionHandler注解实现全局异常捕获。对于同时兼容Web和Ajax请求的情况,可以判断是否是Ajax请求,并返回不同的响应格式。
以下是一个简单的示例代码:
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.StringHttpMessageConverter;
 
import javax.servlet.http.HttpServletRequest;
 
@ControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception e, WebRequest request, HttpServletRequest servletRequest) {
        // 判断是否是Ajax请求
        boolean isAjax = "XMLHttpRequest".equals(servletRequest.getHeader("X-Requested-With"));
 
        // 定义错误信息
        String errorMessage = "发生错误: " + e.getMessage();
 
        if (isAjax) {
            // 如果是Ajax请求,返回JSON格式的错误信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .contentType(new StringHttpMessageConverter().getSupportedMediaTypes().get(0))
                    .body("{\"errorMessage\": \"" + errorMessage + "\"}");
        } else {
            // 如果不是Ajax请求,可以返回错误页面或者ModelAndView
            // 这里简单返回错误信息字符串
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorMessage);
        }
    }
}在上述代码中,我们定义了一个全局异常处理器GlobalExceptionHandler,并使用@ControllerAdvice注解标记。在异常处理方法handleException中,我们通过判断请求头X-Requested-With来判断是否是Ajax请求,并根据不同的请求类型返回不同的响应格式。对于Ajax请求,返回JSON格式的响应;对于非Ajax请求,返回字符串格式的错误信息。这样就可以同时兼容Web和Ajax请求的全局异常处理。
评论已关闭