springMVC-統一參數驗證&業務異常優雅地處理

往往爲了程序的健壯性,有時候不得不時刻提防異常的發生,一般做法就是能try的地方儘量try住。但是太過繁瑣,對業務開發非常不友好。如何纔可以不關心這類異常呢?全部往外拋呢。

如何優雅地處理?

聲明一個全局異常捕獲的切

/**
 * 統一異常處理:針對沒有顯式捕獲異常的controller
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandlerAdvice {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public BaseJsonResponse handleException(Exception e) {
        log.error("sys error", e);
        //參數驗證失敗,例如非空驗證,日期格式驗證等
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            FieldError fieldError = methodArgumentNotValidException.getBindingResult().getFieldError();
            String errorMsg = fieldError.getDefaultMessage();
            return new BaseJsonResponse().error(1, fieldError.getField() + errorMsg);
        } else//TODO 這裏可以定製化業務異常
            return new BaseJsonResponse().error(1, e.getMessage());
    }
}

demo代碼

    @RequestMapping(value = "/xxx.json", method = RequestMethod.POST)
    public @ResponseBody BaseResponse xxx(@Valid @RequestBody XxxReq req) {
    }
    
    @Data
    public class XxxReq {
        @NotNull
        private Integer id;
        @NotNull
        private Integer userId;
        @NotNull
        @Pattern(regexp = GlobalVar.DATE_PATTERN_YMD, message = GlobalVar.DATE_PATTERN_YMD_ERROR)
        private String date;
        @NotNull
        private Integer type;
    }

效果

2019-09-26 10:48:02.872 [http-apr-8080-exec-1] INFO 
                c.q.filter.HttpLogTraceFilter - reqBody={"id":123,"name":"xx"}
2019-09-26 10:48:02.872 [http-apr-8080-exec-1] INFO 
                c.q.filter.HttpLogTraceFilter - respBody={"result":1,"message":"date不能爲null"}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章