java - 使用全局异常处理程序在 SpringBoot 应用程序中处理 BindException
问题描述
我有一个带有发布请求的控制器。我正在尝试使用简单的 NotNull 注释来验证 POJO。我正在使用 ControllerAdvice 来处理异常。
@PostMapping("/something")
public MyResponse post(@Valid MyRequest request) {
// nevermind...
}
public class MyRequest {
@NotNull
private Integer something;
// Getters setters nevermind...
}
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = BindException.class)
protected ResponseEntity<Object> handleBindException(RuntimeException ex, WebRequest request) {
return handleExceptionInternal(...);
}
}
所以我正在尝试使用它,但是当我启动应用程序时,我得到了以下信息:
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 org.springframework.validation.BindException]: {protected org.springframework.http.ResponseEntity com.liligo.sponsoredads.controller.RestResponseEntityExceptionHandler.handleBindException(java.lang.Exception,org.springframework.web.context.request.WebRequest), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest) throws java.lang.Exception}
所以我想为 BindExceptions 创建自己的处理程序,但是当我为 BindException 类创建 ExceptionHandler 时,spring 应用程序没有启动。如果我注释掉 handleBindException 方法,则应用程序启动,如果发生 BindException,它只会返回 400 并注销错误,但没有任何内容作为响应正文发回。
为 BindExceptions 创建自定义处理程序的解决方案是什么?
解决方案
我发现问题是因为 ResponseEntityExceptionHandler 已经有一个方法来处理 BindExceptions。这意味着您不能为此“覆盖”异常处理。许多异常也是如此(参见类 ResponseEntityExceptionHandler:106)。因此,如果您想创建自己的绑定异常处理程序,则需要覆盖超类中处理它的方法。它看起来像这样:
@Override
protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
return handleExceptionInternal(...);
}
有了它,您可以退回任何您需要的东西。所以我只找到了这个解决方案,如果有人知道其他解决方案,请不要犹豫在这里写:)
推荐阅读
- android - addListenerForSingleValueEvent 不执行 onDataChange() 里面的代码
- firebase - Firebase 云函数如何使用 Admin SDK 向主题发送消息?
- javascript - 一个函数正在为所有包含相同类的 div 运行。我怎样才能摆脱它?
- c++ - 在一个 TU 内破坏 ODR?
- java - 如何从字符串中创建类的新对象?
- wso2 - 无法在 WSO2 上部署 twilio 连接器
- security - 执行主节点提供的源代码的工作节点
- reactjs - 为 useHistory 钩子模拟 react-router-dom 会导致以下错误 - TS2698: Spread types may only be created from object types
- jquery - 冲突 jquery 和引导程序
- node.js - 如何在 Mongoose 数据的集合(模型)中正确填充文档