【问题标题】:Get to the root validation cause找到根本验证原因
【发布时间】:2021-01-05 21:56:29
【问题描述】:

我有一个 RestController 来验证其输入:

class Item {}
class ItemHolder {
  Item item;
}

@RestController
public class ItemRestController {
    @GetMapping
    public String get(@Valid ItemHolder itemHolder) { }
}

我有一个参数转换器,它会抛出带有重要消息的自定义异常:

class CannotConvertException extends RuntimeException {}

class ItemConverter implements Converter<String, Item> {
  @Override
  public Item convert(String value) {
    throw new CannotConvertException("Important failure message: " + value);
  }
}

我还有一个异常处理程序:

@ControllerAdvice
class ResponseExceptionHandler extends ResponseEntityExceptionHandler {
  @Override
  protected ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {

        // How to get only the message from CannotConvertException here?
    }

handleBindException 中,我收到的消息(即ex.getMessage())类似于:

org.springframework.validation.BeanPropertyBindingResult: 1 个错误 字段'item'上的对象'itemHolder'中的字段错误:拒绝值[非常糟糕的值];代码 [typeMismatch.itemHolder.item,typeMismatch.item,typeMismatch.com.example.Item,typeMismatch];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [itemHolder.item,item];论据 [];默认消息[项目]];默认消息 [无法将类型“java.lang.String[]”的值转换为所需类型“com.example.Item”;嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [com.example.Item] 的值“非常糟糕的值”;嵌套异常是 com.example.CannotConvertException: Important failure message: very bad value]

如果不使用诸如字符串解析或反射之类的技巧,我将如何确保异常处理程序只能到达Important failure message: very bad value 部分,而没有之前的所有噪音?

如果这是更好的选择,我可以更换转换器。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    尝试抛出MethodArgumentTypeMismatchException,而不是转换器中的自定义异常,并在建议中添加一个新方法来处理这些类型的异常。

    这应该可以解决您的问题!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多