【发布时间】:2020-07-02 10:40:06
【问题描述】:
我的 Spring DTO 中有一个枚举字段,我在 @RestController 中使用它。我希望在此枚举字段验证失败时创建自定义错误消息:
public class ConversionInputDto {
// validation annotations
private BigDecimal sourceAmount;
// enum field
@NotNull(message = ERROR_EMPTY_VALUE)
private CurrencyFormat targetCurrency;
// no-args constructor and getters
}
在我的情况下,将输入作为字符串接收并创建 custom annotation 似乎有点过头了,而我知道的另一种选择通过 @ControllerAdvise 捕获所有 InvalidFormatException 错误并为它们返回相同的错误(因此,用户提交例如数字属性的字符串输入将得到相同的错误消息):
@ExceptionHandler(InvalidFormatException.class)
public void handleInvalidEnumAndAllOtherInvalidConversions(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value(), ERROR_MESSAGE);
}
当前默认验证错误太长,我想让它更人性化,例如“无效的货币格式值。请在...之间选择。”:
"无效的 JSON 输入:无法反序列化类型的值
com.foreignexchange.utilities.CurrencyFormat来自字符串 \"test\": 不是枚举类接受的值之一:[AUD, PLN, MXN, USD, 加元];嵌套异常是 com.fasterxml.jackson.databind.exc.InvalidFormatException:不能 反序列化类型的值com.foreignexchange.utilities.CurrencyFormat来自字符串 \"test\": 不是枚举类接受的值之一:[AUD, PLN, MXN, USD, CAD]\n 在 [Source: (PushbackInputStream);行:3,列:20] (通过参考链: com.foreignexchange.models.ConversionInputDto[\"targetCurrency\"])",
有没有优雅的方法来解决这个问题?也许在@ExceptionHandler 中添加一些额外的逻辑来检查哪个字段验证失败?
【问题讨论】:
-
您可以尝试registering a custom deserializer 用于您的枚举类,它会抛出自定义异常并提供更用户友好的消息
-
我希望避免 instanceOf 检查,但这是我能找到的最短方法。谢谢!
标签: java spring spring-boot rest enums