1. 程式人生 > 其它 >springboot全域性異常處理(傳入引數校驗)

springboot全域性異常處理(傳入引數校驗)

1.匯入依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2.建立全域性異常處理類

@RestControllerAdvice
public class ProjectExceptionAdvice {

//    攔截所有異常錯誤,如果沒有自定義 只要有報錯就會被這裡攔截
@ExceptionHandler public ApiRequest doException(Exception e){ e.printStackTrace();// 輸入異常到控制檯 return new ApiRequest(false,"伺服器出現異常,請稍後再試"); } // 自定義攔截, 攔截傳入引數非空判斷 @ExceptionHandler(MethodArgumentNotValidException.class) public ApiRequest NotValidException(MethodArgumentNotValidException e){ e.printStackTrace(); String message
= e.getBindingResult().getFieldError().getDefaultMessage(); return ApiRequest.faild(message); } }

3.使用

【傳入引數Param類】

@Data
public class LoginParam {
    @NotBlank(message = "賬號不能為空")
    private String username;
    private String password;


}

【Controller】

接收引數加入該註解:

@Validated

ok