1、新建立一个捕获异常的实体类
如:LeeExceptionHandler
1 package com.leecx.exception; 2 3 import javax.servlet.http.HttpServletRequest; 4 import javax.servlet.http.HttpServletResponse; 5 6 import org.springframework.web.bind.annotation.ControllerAdvice; 7 import org.springframework.web.bind.annotation.ExceptionHandler; 8 import org.springframework.web.servlet.ModelAndView; 9 10 @ControllerAdvice 11 public class LeeExceptionHandler { 12 13 public static final String DEFAULT_ERROR_VIEW = "error"; 14 15 16 17 @ExceptionHandler(value = Exception.class) 18 public Object errorHandler(HttpServletRequest reqest, HttpServletResponse response, Exception e) throws Exception { 19 20 e.printStackTrace(); 21 22 if (isAjax(reqest)) { 23 return response; 24 } else { 25 ModelAndView mav = new ModelAndView(); 26 mav.addObject("exception", e); 27 mav.addObject("url", reqest.getRequestURL()); 28 mav.setViewName(DEFAULT_ERROR_VIEW); 29 return mav; 30 } 31 } 32 33 34 public static boolean isAjax(HttpServletRequest httpRequest){ 35 return (httpRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals( httpRequest.getHeader("X-Requested-With").toString()) ) ; 36 } 37 38 39 }
在类上面加入注解:@ControllerAdvice
在处理方法上面加入注解@ExceptionHandler(value = Exception.class)
然后设置相应的业务处理。跳转到 特需的处理错误的友好业务界面。
原文地址:https://www.cnblogs.com/yinfengjiujian/p/8799245.html
时间: 2024-10-27 12:15:58