業務規範之統一異常處理和統一響應

業務規範之統一異常處理和統一響應

###業務規範之springboot整合swagger2
###業務規範之統一驗證
###業務規範之統一返回體
###業務規範之統一異常處理和統一響應

四、統一異常處理

統一api異常:

public class APIException extends RuntimeException {

    private int code;

    private String message;

    public APIException(int code, String message){
        super(message);
        this.code = code;
        this.message = message;
    }

    public APIException(String message){
        this(ResultEnum.FAILED.getCode(),message);
    }

    public APIException(){
        this(ResultEnum.FAILED.getCode(),ResultEnum.FAILED.getMessage());
    }

}

統一異常處理:

@RestControllerAdvice
public class ExceptionControllerAdvice {

    /**
     * 全局處理參數校驗未通過異常
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ErrorResponse<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ErrorResponse<String> errorResponse = new ErrorResponse<>();
        // 獲得默認消息
        String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        errorResponse.setFailed(ResultEnum.VALIDATE_FAILED.getCode(),
                ResultEnum.VALIDATE_FAILED.getMessage()+": "+defaultMessage);
        return errorResponse;
    }

    /**
     * 全局處理api異常
     * @param e
     * @return
     */
    @ExceptionHandler(value = APIException.class)
    public ErrorResponse<String> apiExceptionHandler(APIException e){
        ErrorResponse<String> errorResponse = new ErrorResponse<>();
        errorResponse.setFailed(ResultEnum.FAILED.getMessage()+e.getMessage());
        return errorResponse;
    }

    /**
     * 全局處理exception
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ErrorResponse<String> exceptionHandler(Exception e){
        ErrorResponse<String> errorResponse = new ErrorResponse<>();
        errorResponse.setFailed(ResultEnum.ERROR.getCode(),ResultEnum.ERROR.getMessage());
        return errorResponse;
    }


}

五、統一響應

統一響應體:

@RestControllerAdvice
public class ResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 全局處理響應數據
     */

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 當返回的數據不是BaseResponse 的時候,執行 beforeBodyWrite 方法
        // ① 獲得返回參數類型
        System.out.println(methodParameter);

        Type genericParameterType = methodParameter.getGenericParameterType();
        String typeName = genericParameterType.getTypeName();
        String name = "org.springframework.http.ResponseEntity";
        // 對swagger的請求不做處理
        if (typeName.contains(name)) {
            return false;
        }
        String typeName2 = ErrorResponse.class.getTypeName();
        // 對錯誤的返回請求不做處理
        if (StrUtil.containsAny(typeName, typeName2)){
            return false;
        }
        // 若是錯誤的則直接返回
        return ! StrUtil.containsAny(typeName, BaseResponse.class.getTypeName());
    }

    /*
        只有 supports 方法返回 true的時候纔會執行以下方法
     */
    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        /**
         *  這裏只對正確的做處理
         */
        BaseResponse<Object> baseResponse = new BaseResponse<>();
        baseResponse.data =data;
        if(methodParameter.getGenericParameterType().equals(String.class)){
            ObjectMapper objectmapper = new ObjectMapper();
            try {
                return objectmapper.writeValueAsString(baseResponse);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                throw new APIException("返回String類型錯誤");
            }
        }
        return baseResponse;
    }

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