java - Spring 验证失败时枚举字段上的自定义错误消息

标签 java spring spring-boot rest enums

我的 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 type com.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/

相关文章:

java - 通过 AS1 或 AS2 或 AS3 协议(protocol)将 EDI 或 XML 文档从一台机器传输到另一台机器

mysql - Grails 中属性的自引用关系?

java - 在 Spring 中访问计划任务

java - 是否可以在微服务应用程序中代理 POJO?

java - 无法获取 getResponseCode

java - intellij tomcat "copying resources"花费太多时间

java - 如何将测试代码与生产代码一起重构?

spring - 如何定义多个initBinder

amazon-web-services - 部署在 Elastic Beanstalk Java 环境上的 Spring Boot 应用程序返回 502

java - 带有 AsyncRestTemplate Netty 客户端的 Spring Boot 失败