两种方式:
springboot Restful使用@ControllerAdvice、@ExceptionHandler、@ResponseBody实现全局异常处理
@ControllerAdvice 注解定义全局异常处理类
@ExceptionHandler 指定自定义错误处理方法拦截的异常类型
同一个异常被小范围的异常类和大范围的异常处理器同时覆盖,会选择小范围的异常处理器
一.
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.servlet.HandlerExceptionResolver;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@Commpentpublic class GlobalException implements HandlerExceptionResolver { private static final Logger logger= LoggerFactory.getLogger(GlobalException.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //打印控制台 ex.printStackTrace(); //写日志 logger.debug("debug日志"); logger.info("info日志"); logger.error("系统发生异常",ex); //发邮件,使用jmail工具报 //展示友好错误页面 ModelAndView modelAndView=new ModelAndView("error/exception"); return modelAndView; }}
二.
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ModelAndView resolveException(HttpServletRequest request, Exception ex) throws Exception { ModelAndView mav = new ModelAndView(); System.out.println(ex.getMessage()); mav.addObject("errMsg", ex.getMessage()); mav.setViewName("error"); return mav; }}