1. 程式人生 > >Spring-全局異常攔截

Spring-全局異常攔截

types formate getpath 選擇 全局異常 stat not 裏的 json

Spring MVC那一篇裏提到了異常攔截來做參數校驗返回,那裏是對特定的 controller 做異常捕捉,但是我們也可以選擇全局攔截處理

快速開始

@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    /***
    * 參數綁定異常
    * @date 2018/10/16
    * @param exception HttpMessageNotReadableException
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Long> messageNotReadable(HttpMessageNotReadableException exception){
        InvalidFormatException formatException = (InvalidFormatException)exception.getCause();
        List<JsonMappingException.Reference> e = formatException.getPath();
        String fieldName = "";
        for (JsonMappingException.Reference reference :e){
            String fieldName = reference.getFieldName();
        }
        logger.error("參數不匹配"+exception);
        return Result.createFailResult(fieldName+"參數類型不匹配");
    }

    /***
    * 全局異常,如果沒有匹配到上述準確的異常,都會到這裏來處理
    * @date 2018/10/16
    * @param e 沒有匹配到的全局異常
    */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public Result<String> all(Exception e){
        //這裏的log使用了“,”,這樣能把異常的堆棧信息全部打印出來,更容易定位bug
        logger.error("異常:",e);
        return Result.createFailResult("工程搶救中……請稍後再試");
    }
}

@ControllerAdvice

@ControllerAdvice 默認監控所有的 @RequestMapping 方法,也可以對指定過濾的條件:

// 監控所有的被@RestController註解的Controllers類 
@ControllerAdvice(annotations = RestController.class)

// 監控特定的包下的Controllers類
@ControllerAdvice("org.example.controllers")

// 監控指定類的Controllers類
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})

Spring-全局異常攔截