【发布时间】:2023-04-10 14:46:05
【问题描述】:
我正在寻找一种方法来处理在将请求参数绑定到 DTO 字段期间引发的自定义异常。
我在 Spring Boot 应用程序中有一个控制器,如下所示
@GetMapping("/some/url")
public OutputDTO filterEntities(InputDTO inputDTO) {
return service.getOutput(inputDTO);
}
输入DTO的字段很少,其中一个是枚举类型
public class InputDTO {
private EnumClass enumField;
private String otherField;
/**
* more fields
*/
}
用户会以这种方式点击网址
localhost:8081/some/url?enumField=wrongValue&otherField=anyValue
现在,如果用户为 enumField 发送了错误的值,我想抛出带有特定消息的 CustomException。在 binder 中实现 enum 实例创建和抛出异常的过程
@InitBinder
public void initEnumClassBinder(final WebDataBinder webdataBinder) {
webdataBinder.registerCustomEditor(
EnumClass.class,
new PropertyEditorSupport() {
@Override
public void setAsText(final String text) throws IllegalArgumentException {
try {
setValue(EnumClass.valueOf(text.toUpperCase()));
} catch (Exception exception) {
throw new CustomException("Exception while deserializing EnumClass from " + text, exception);
}
}
}
);
}
问题是当抛出异常时无法处理
@ExceptionHandler(CustomException.class)
public String handleException(CustomException exception) {
// log exception
return exception.getMessage();
}
Spring 使用 BindException 包装初始异常。该实例包含我的初始错误消息,但与其他对我来说多余的文本连接在一起。我不认为解析和子串该消息是好的......
我错过了什么吗?从初始获取消息的正确方法是什么 这里有自定义异常?
【问题讨论】:
-
我检查了第一件事。 BindException 实例的getClause() 方法返回null。
标签: java spring-boot exception-handling