我的 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);
}
当前的默认验证错误太长,我想让它更加用户友好,例如“无效的货币格式值。请选择......”:
"Invalid JSON input: Cannot deserialize value of type
com.foreignexchange.utilities.CurrencyFormat
from String \"test\": not one of the values accepted for Enum class: [AUD, PLN, MXN, USD, CAD]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of typecom.foreignexchange.utilities.CurrencyFormat
from String \"test\": not one of the values accepted for Enum class: [AUD, PLN, MXN, USD, CAD]\n at [Source: (PushbackInputStream); line: 3, column: 20] (through reference chain: com.foreignexchange.models.ConversionInputDto[\"targetCurrency\"])",
有没有一种优雅的方法来解决这个问题?也许在 @ExceptionHandler
中使用一些额外的逻辑来检查哪个字段验证失败?
最佳答案
感谢这些评论,我找到了一个解决方案,使用 isAssignableFrom()
为失败的枚举验证提供自定义错误消息:
@ExceptionHandler(InvalidFormatException.class)
public void handleOfflineBankApi(HttpServletResponse response, InvalidFormatException ex) throws IOException {
if (ex.getTargetType().isAssignableFrom(CurrencyFormat.class)) {
response.sendError(HttpStatus.BAD_REQUEST.value(), Constants.ERROR_INVALID_CURRENCY_FORMAT);
} else {
response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
}
关于java - Spring 验证失败时枚举字段上的自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60788627/