Spring Boot系列(四):统一异常管理和错误页处理

简介

统一异常管理和错误页处理是项目中我认为比较常用的,所以也写一写。

统一异常管理

直接贴代码:

/**
 * @author: uncle
 * @apdateTime: 2018-01-10 17:01
 */
@ControllerAdvice// 注解将作用在所有注解了@RequestMapping的控制器的方法上
public class ExceptionHandling {

    @ExceptionHandler(Exception.class)// 用于全局处理控制器里的异常
    @ResponseBody
    public ModelAndView error(HttpServletRequest rq, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exception", e);
        modelAndView.addObject("url", rq.getRequestURL());
        modelAndView.setViewName("error");
        return modelAndView;
    }

    @ModelAttribute // 此处使用@ModelAttribute注解将键值对添加到全局,所有注解了@RequestMapping的方法可获得此键值对
    public void addAttributes(Model model) {
        model.addAttribute("msg", "额外信息");
    }

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) { // https://www.cnblogs.com/AloneSword/p/3998943.html
        webDataBinder.setDisallowedFields("id");
    }
}

错误页处理

/**
 * @author: uncle
 * @apdateTime: 2018-01-10 17:20
 */
@Configuration
public class ErrorHandling {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return container -> {
            container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
            container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500"));
            container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
        };
    }
}
Last modification:January 10th, 2018 at 06:32 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment