如何解决或编写相同的异常处理程序在春季启动?



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

org.springframework.beans。BeanInstantiationException: Failed to实例化[org.springframework.web.servlet。HandlerExceptionResolver]:工厂方法'handlerExceptionResolver'抛出异常;嵌套异常是java.lang.IllegalStateException:模糊@ExceptionHandler方法映射为[class javax. validate . constraintviolationexception]:{公共az.expressbank.task.response.ExceptionResponseaz.expressbank.task.api.controller.EmployeeRestApiExceptionHandlerController.catchWhenTypeWrongEmailRegisterPage (javax.validation.ConstraintViolationException),公共az.expressbank.task.response.ExceptionResponseaz.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,您可以参考这个示例,了解如何为每个验证器定义错误代码,并找出该失败验证器对应的错误代码。

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

相关内容

最新更新