![](/img/trans.png)
[英]Spring Boot - how to differentiate between validation for @PathVariable and query params (@RequestParam)
[英]Spring Boot PathVariable Validation Message
我想验证端点的PathVariable。 实际上,这不是验证,因为它是由Java本身完成的。 例如,如果PathVariable类型为Integer,并且我将String传递给它,它将抛出如下所示的内容: Failed to convert value of type [java.lang.String] to required type [java.lang.Long]...
这是响应消息。 如何设置自定义消息(例如:年龄必须是数字)? 我知道我可以创建一个自定义验证器并将其与注释一起使用,但是由于我有很多端点,因此我将不得不为每个PathVariable创建大量验证器-看起来有些不对劲,因为我知道必须有一个只是更简单的方法。 我错了吗?
您可以为抛出的MethodArgumentTypeMismatchException
创建一个处理程序:
@RestControllerAdvice
public class ExceptionControllerAdvice {
@Inject
private MessageSource messageSource;
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleTypeMismatch(MethodArgumentTypeMismatchException e) {
// Return custom message from messageSource using e.getRequiredType()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.