Spring Boot常見的錯誤處理方法有三種,在實際使用的過程中選擇其中一種即可。
方法一:Spring Boot 將所有的錯誤默認映射到/error, 實現(xiàn)ErrorController。
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();
}
}
自定義一個類實現(xiàn)ErrorController,當系統(tǒng)發(fā)生404或者500錯誤的時候,就會自動進入到自定義的錯誤頁面中,這要求在resources文件里面的templates文件內(nèi)部建立一個error文件夾,里面放自定義錯誤頁面的模板即可。當訪問/error這個路徑的時候,也會進入錯誤頁面。
方法二:添加自定義的錯誤頁面。
1)html靜態(tài)頁面:在resources/public/error/ 下定義 如添加404頁面: resources/public/error/404.html頁面,中文注意頁面編碼
2)模板引擎頁面:在templates/error/下定義 如添加5xx頁面: templates/error/5xx.ftl
注:templates/error/ 這個的優(yōu)先級比較 resources/public/error/高,當系統(tǒng)發(fā)生錯誤的時候,會自動去加載那些定義好的頁面。
方法三:使用注解@ControllerAdvice,推薦使用。
編寫一個全局異常處理的類,這個類里面可以分門別類處理各種異常,可以對每一種異常提供一種自定義頁面,使用戶體驗更加友好。這里僅僅處理了運行時異常和空指針異常。
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模板文件。