
基于spring注解实现异常拦截统一处理,主要使用到两个注解
1.@ControllerAdvice,它是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。
2.@ExceptionHandler,用于对于不同的异常进行拦截,注解value可以自定义异常。
自定义异常类
BusinessException,PageException
public class BusinessException extends RuntimeException {
private Integer code=0;
public BusinessException(){
super();
}
public BusinessException(String message){
super(message);
}
public BusinessException(int code,String message){
super(message);
this.code= code;
}
public Integer getCode() {
return code;
}
}
public class PageException extends RuntimeException {
private int code;
public PageException(){
super();
}
public PageException(String message){
super(message);
}
public PageException(int code,String message){
super(message);
this.code= code;
}
}
自定义错误消息
public class ExceptionMessage {
public Integer type;
public Integer code;
public String msg;
public Object content;
public String exceptionStack;
}
异常统一拦截处理
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger= LoggerFactory.getLogger(GlobalExceptionHandler.class);
public static final String DEFAULT_404_VIEW = "404error";
public static final Integer BusinessException=1;
public static final Integer RunTimeException=2;
@Autowired
private LogInterface logInterface;//日志接口,用于将异常日志存入持久层
@ExceptionHandler(value = PageException.class)
public ModelAndView pageExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
ModelAndView mav = new ModelAndView();
mav.addObject("message", e.getMessage());
mav.setViewName(DEFAULT_404_VIEW);
return mav;
}
@ExceptionHandler(value = BusinessException.class)
@ResponseBody
public ExceptionMessage businessExceptionHandler(HttpServletRequest req, Exception e) {
try{
BusinessException exception= (BusinessException) e;
ExceptionMessage message = generateMessage(exception);
logInterface.addExceptionLog(message);
return message;
}catch (Exception ex){
logger.error("businessExceptionHandler error.",ex);
ExceptionMessage message= new ExceptionMessage();
message.msg= ex.getMessage();
message.exceptionStack= ExceptionUtils.getFullStackTrace(ex);
return message;
}
}
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public ExceptionMessage runtimeExceptionHandler(HttpServletRequest req, Exception e) {
try{
ExceptionMessage message = generateMessage(e);
message.type= RunTimeException;
logInterface.addExceptionLog(message);
return message;
}catch (Exception ex){
logger.error("runtimeExceptionHandler error.",ex);
ExceptionMessage message= new ExceptionMessage();
message.msg= ex.getMessage();
message.exceptionStack= ExceptionUtils.getFullStackTrace(ex);
return message;
}
}
private ExceptionMessage generateMessage(Exception e){
logger.error("runtimeException", e);
ExceptionMessage message = new ExceptionMessage();
message.code = 0;
message.msg = e.getMessage();
message.content = "do your self.";
message.exceptionStack = ExceptionUtils.getFullStackTrace(e);
return message;
}
}
网友评论