Spring Boot常见的错误处理方法有三种,在实际使用的过程中选择其中一种即可。
package com.lemon.springboot.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.web.ErrorController; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/error") public class BaseErrorController implements ErrorController { public static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class); @Override public String getErrorPath() { logger.info("这是错误页面"); return "error/error"; } @RequestMapping public String error() { return getErrorPath(); } }
自定义一个类实现ErrorController,当系统发生404或者500错误的时候,就会自动进入到自定义的错误页面中,这要求在resources文件里面的templates文件内部建立一个error文件夹,里面放自定义错误页面的模板即可。当访问/error这个路径的时候,也会进入错误页面。
1)html静态页面:在resources/public/error/ 下定义 如添加404页面: resources/public/error/404.html页面,中文注意页面编码 2)模板引擎页面:在templates/error/下定义 如添加5xx页面: templates/error/5xx.ftl
注:templates/error/ 这个的优先级比较 resources/public/error/高,当系统发生错误的时候,会自动去加载那些定义好的页面。
编写一个全局异常处理的类,这个类里面可以分门别类处理各种异常,可以对每一种异常提供一种自定义页面,使用户体验更加友好。这里仅仅处理了运行时异常和空指针异常。
package com.lemon.springboot.exception; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.servlet.ModelAndView; /** * @author lemon */ @ControllerAdvice public class ErrorExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(ErrorExceptionHandler.class); /** * 处理运行时异常的方法 * @param exception 运行时异常 * @return ModelAndView实例对象 */ @ExceptionHandler({RuntimeException.class}) @ResponseStatus(HttpStatus.OK) public ModelAndView processException(RuntimeException exception) { logger.info("自定义异常处理-RuntimeException"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", exception.getMessage()); modelAndView.setViewName("500"); return modelAndView; } /** * 处理空指针异常的页面 * @param exception 空指针异常 * @return ModelAndView实例对象 */ @ExceptionHandler({NullPointerException.class}) @ResponseStatus(HttpStatus.OK) public ModelAndView processException(NullPointerException exception) { logger.info("自定义异常处理-NullPointerException"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("message", exception.getMessage()); modelAndView.setViewName("nullPointer"); return modelAndView; } }
这里使用到了ModelAndView,必须在templates文件夹下建立error文件夹,然后放500.html和nullPointer.html模板文件。
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句