美文网首页
在SpringBoot中配置全局异常处理

在SpringBoot中配置全局异常处理

作者: 阿格里 | 来源:发表于2018-08-13 17:21 被阅读0次

    @ControllerAdvice: 定义一个全局的异常处理类,同时也可以使用@RestControllerAdvice返回JSON格式。

    @ControllerAdvice
    public class GlobalExceptionHandler {
        //......
    }
    

    @ExceptionHandler: 统一的处理异常,可以自定义异常类型。
    比如:定义 @ExceptionHandler({NullPointerException.class, BusinessException.class}) 来处理空指针异常和一个我们自定义的一个业务异常。

    @ExceptionHandler({NullPointerException.class, BusinessException.class})
    public Object businessHandler(HttpServletRequest request, BusinessException e) throws BusinessException {
          // ......
    }
    

    我们创建一个全局的异常处理类:GlobalExceptionHandler

    import org.apache.log4j.Logger;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * 异常全局处理类
     */
    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        private Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
    
        @ExceptionHandler(Exception.class)
        public Object exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
            logger.error(e);
    
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("url", request.getRequestURL());
            modelAndView.addObject("exception", e);
            modelAndView.setViewName("error");
    
            return modelAndView;
    
        }
    
        @ExceptionHandler(BusinessException.class)
        public Object businessHandler(HttpServletRequest request, BusinessException e) throws BusinessException {
            logger.error(e);
    
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("url", request.getRequestURL());
            modelAndView.addObject("exception", e);
            modelAndView.setViewName("business_error");
    
            return modelAndView;
    
        }
    
        /**
         * 判断是否为一个ajax请求
         * @param request
         * @return
         */
        public boolean isAjaxRequest(HttpServletRequest request) {
            String header = request.getHeader("X-Requested-With");
            boolean isAjax = "XMLHttpRequest".equals(header) ? true : false;
            return isAjax;
        }
    
    }
    

    接下来我们定义一个业务异常类:BusinessException,继承RuntimeException

    public class BusinessException extends RuntimeException {
    
        public BusinessException() {
            super();
        }
    
        public BusinessException(String message) {
            super(message);
        }
    
    }
    

    相关文章

      网友评论

          本文标题:在SpringBoot中配置全局异常处理

          本文链接:https://www.haomeiwen.com/subject/xdkubftx.html