如何在 spring 引导中解决或编写相同的异常处理程序?

How to solve or write the same exception handler in spring boot?

如您所见,我使用了两个具有相同参数的错误捕获方法,但是当我 运行 它时,我得到以下错误。我同样使用它们的原因是因为 spring boot 也会抛出相同的异常 @Email 和 @Size 所以我想捕获它们并显示我自己的错误输出。我怎样才能 运行 在不同的时间都没有错误?比如当你不输入@符号时,我想通过闪现相关的错误输出来显示我自己的错误,或者如果密码长度较短,我想显示相关的错误输出。

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class javax.validation.ConstraintViolationException]: {public az.expressbank.task.response.ExceptionResponse az.expressbank.task.api.controller.EmployeeRestApiExceptionHandlerController.catchWhenTypeWrongEmailRegisterPage(javax.validation.ConstraintViolationException), public 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;
        
            }

每种类型的异常只能有一个异常处理程序。这意味着您必须依靠检查异常实例的状态来确定失败的根本原因。

请注意,如果在 @PathVariable@RequestParam 上验证失败,它将抛出 ConstraintViolationException,而如果在验证请求正文时失败,则会抛出 MethodArgumentNotValidException

对于ConstraintViolationException,可以参考这个example如何定义每个验证器的错误码,并找出该失败验证器对应的错误码。

对于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 () 
    });
}