如您所見,我使用了兩個引數相同的錯誤捕獲方法,但是當我運行它時,出現以下錯誤。我使用它們的原因是因為 spring boot 也拋出相同的例外 @Email 和 @Size 所以我想捕獲它們并顯示我自己的錯誤輸出。如何在不同時間運行而不會出錯?例如,當你不輸入@符號時,我想通過閃爍相關錯誤輸出來顯示我自己的錯誤,或者如果密碼長度很短,我想顯示相關錯誤輸出。
org.springframework.beans.BeanInstantiationException:無法實體化[org.springframework.web.servlet.HandlerExceptionResolver]:工廠方法'handlerExceptionResolver'拋出例外;嵌套例外是 java.lang.IllegalStateException: Ambiguous @ExceptionHandler 方法映射為 [class javax.validation.ConstraintViolationException]: {public az.expressbank.task.response.ExceptionResponse az.expressbank.task.api.controller.EmployeeRestApiExceptionHandlerController.catchWhenTypeWrongEmailRegisterPage(javax .validation.ConstraintViolationException), 公共 az.expressbank.task.response.ExceptionResponse az.expressbank.task.api.controller.EmployeeRestApiExceptionHandlerController.catchWhenTypeShortPasswordRegisterPage(javax.validation.ConstraintViolationException)}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExceptionResponse catchWhenTypeWrongEmailRegisterPage(ConstraintViolationException exception) {
Exception exception1=new Exception();
ExceptionResponse exceptionResponse = new ExceptionResponse();
exceptionResponse.setMessage(Message.PASSWORD_MUST_NOT_BE_SHORT.getMessage());
exceptionResponse.setCode(550);
return exceptionResponse;
}
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExceptionResponse catchWhenTypeShortPasswordRegisterPage(ConstraintViolationException exception) {
ExceptionResponse exceptionResponse = new ExceptionResponse();
exceptionResponse.setMessage(Message.WRONG_FORMAT.getMessage());
exceptionResponse.setCode(551);
return exceptionResponse;
}
uj5u.com熱心網友回復:
對于每種型別的例外,您只能有一個例外處理程式。這意味著您必須依靠檢查例外實體的狀態來確定失敗的根本原因。
請注意,ConstraintViolationException如果驗證失敗,它將拋出,@PathVariable或者如果驗證請求正文失敗,@RequestParam則拋出MethodArgumentNotValidException。
對于ConstraintViolationException,您可以參考這個例子來了解如何為每個驗證器定義錯誤代碼,并找出該失敗驗證器對應的錯誤代碼。
對于MethodArgumentNotValidException,您可以參考以下代碼以找出導致失敗的驗證器的想法。
@ExceptionHandler(MethodArgumentNotValidException.class)
public ExceptionResponse handle(MethodArgumentNotValidException exp) {
BindingResult bindingResult = exp.getBindingResult();
bindingResult.getAllErrors().forEach(err -> {
err.getCode() // simple class name of the validator annotation that cause the exception such as Email /Size
err.getDefaultMessage ()
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/321960.html
上一篇:基于FK檢索關系上的欄位
