1. 程式人生 > >Spring Boot 請求錯誤處理

Spring Boot 請求錯誤處理

.cn span .get final log cto imp pla mage

方法一:Spring Boot將所有的錯誤映射到/error,實現ErrorController接口

 1 @Controller
 2 @RequestMapping("/error")
 3 public class BaseErrorController implements ErrorController {
 4     private final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);
 5 
 6     @Override
 7     public String getErrorPath() {
8 logger.info("出錯了"); 9 return "error/error"; 10 } 11 12 @RequestMapping 13 public String error() { 14 return getErrorPath(); 15 } 16 }

技術分享         技術分享

請求一個錯誤的地址:localhost:8080/asdf,就會跳轉到 error/error.ftl 頁面。

==============================================================

方法二:添加自定義的錯誤頁面(前提:沒有實現ErrorController接口)

2.1 添加 html 靜態頁面:在resources/public/error/下定義

    如添加404頁面:resources/public/error/404.html頁面(中文註意頁面編碼)

2.2 添加模板引擎頁面:在templates/error下定義

    如添加5xx頁面:templates/error/5xx.ftl;

    添加404頁面: templates/error/404.ftl 。

註:templates/error/ 這個的優先級比 resources/public/error/ 的優先級高。

==============================================================

方法三:使用註解@ControllerAdvice

@ControllerAdvice
public class BaseException {
    private final Logger logger = LoggerFactory.getLogger(BaseException.class);

    /**
     * 統一異常處理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler({RuntimeException.class})//攔截運行時異常(可以攔截自定義異常)
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(RuntimeException exception) {
        logger.info("自定義異常處理--RuntimeException");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exceptionMsg", exception.getMessage());
        modelAndView.setViewName("error/500");
        return modelAndView;
    }

    /**
     * 統一異常處理
     * @param exception
     * @return
     */
    @ExceptionHandler({Exception.class})//攔截總異常
    @ResponseStatus(HttpStatus.OK)
    public ModelAndView processException(Exception exception) {
        logger.info("自定義異常處理--Exception");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("exceptionMsg", exception.getMessage());
        modelAndView.setViewName("error/500");
        return modelAndView;
    }

}

在templates/error下創建500.ftl 來接收展示 ${exceptionMsg}。

Spring Boot 請求錯誤處理