SpringBoot 異常處理

異常處理最佳實踐

根據個人工做經從來看,我主要遵循如下幾點:html

  1. 儘可能不要在代碼中寫try...catch.finally把異常吃掉。
  2. 異常要儘可能直觀,防止被他人誤解
  3. 將異常分爲如下幾類,業務異常,登陸狀態無效異常,(雖已登陸,且狀態有效)未受權異常,系統異常(JDK中定義Error和Exception,好比NullPointerException, ArithmeticException 和 InputMismatchException)
  4. 能夠在某個特定的Controller中處理異常,也能夠使用全局異常處理器。儘可能使用全局異常處理器

使用@ControllerAdvice註釋全局異常處理器

@ControllerAdvice
public class GlobalExceptionHandler implements ApplicationContextAware {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @ExceptionHandler
    public Object businessExceptionHandler(Exception exception, HttpServletRequest req) {
        DtoResult response = new DtoResult();

        if (exception instanceof BusinessException) {
            int code = ((BusinessException) exception).getErrorCode();
            response.setCode(code > 0 ? code : DtoResult.STATUS_CODE_BUSINESS_ERROR);
            response.setMessage(exception.getMessage());
        } else if (exception instanceof NotAuthorizedException) {
            response.setCode(DtoResult.STATUS_CODE_NOT_AUTHORIZED);
            response.setMessage(exception.getMessage());
        } else {
            response.setCode(DtoResult.STATUS_CODE_SYSTEM_ERROR);
            String profile = applicationContext.getEnvironment().getProperty("spring.profiles.active");
            if (profile != GlobalConst.PROFILE_PRD) {
                response.setMessage(exception.toString());
            } else {
                response.setMessage("系統異常");
            }
            logger.error("「系統異常」", exception);
        }

        String contentTypeHeader = req.getHeader("Content-Type");
        String acceptHeader = req.getHeader("Accept");
        String xRequestedWith = req.getHeader("X-Requested-With");
        if ((contentTypeHeader != null && contentTypeHeader.contains("application/json"))
                || (acceptHeader != null && acceptHeader.contains("application/json"))
                || "XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
            HttpStatus httpStatus = HttpStatus.OK;
            if (response.getCode() == DtoResult.STATUS_CODE_SYSTEM_ERROR) {
                httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
            }
            return new ResponseEntity<>(response, httpStatus);
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("detailMessage", response.getMessage());
            modelAndView.addObject("url", req.getRequestURL());
            modelAndView.setViewName("error");
            return modelAndView;
        }
    }
}
  1. 使用@ControllerAdvice生命該類中的@ExceptionHandler做用於全局
  2. 使用@ExceptionHandler註冊異常處理器,能夠註冊多個,可是不能重複,好比註冊兩個方法都用於處理Exception是不行的。
  3. 使用HttpServletRequest中的header檢測請求是否爲ajax, 若是是ajax則返回json(即ResponseEnttiy<>), 若是爲非ajax則返回view(即ModelAndView)

thymeleaf模板標籤解析錯誤

themyleaf默認使用HTML5模式,此模式比較嚴格,好比當標籤沒有正常閉合,屬性書寫不正確時都會報錯,好比如下格式java

# meta標籤沒有閉合
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>程序出錯了 -  智聯</title>
</head>
<body>
<p>程序出錯了...</p>
<p>請求地址:<span th:text="${url}"></span></p>
<p>詳情:<span th:text="${detailMessage}"></span></p>
</body>
</html>

# 屬性v-cloak不符合格式
<div v-cloak></div>

解決方法
能夠在配置文件中增長 spring.thymeleaf.mode=LEGACYHTML5 配置項,默認狀況下是 spring.thymeleaf.mode=HTML5,
LEGACYHTML5 須要搭配第三方庫 nekohtml 才能夠使用。web

# 1.在 pom.xml 中增長以下內容:
<!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

# 2.修改 application.properties 爲:
############################## thymeleaf ##############################
spring.thymeleaf.cache=false
# spring.thymeleaf.mode=HTML5
spring.thymeleaf.mode=LEGACYHTML5
############################## thymeleaf ##############################

參考文檔

themyleaf 參考文檔

異常處理

相關文章
相關標籤/搜索