简体   繁体   English

Spring 启动验证@PathVariable 参数时如何返回自定义错误消息

[英]Spring Boot how to return custom error message when validating @PathVariable parameters

Is it possible to add some custom validation message to path variable?是否可以向路径变量添加一些自定义验证消息?

I have some GET我有一些 GET

  @GetMapping("/v2/tw/{id}")
    public TwDto getTw(Authentication auth, @PathVariable Long id) {

In case of /v2/tw/someString I'd like to catch error and add some custom error message like "invalid tw ID"... How to do that?/v2/tw/someString的情况下,我想捕获错误并添加一些自定义错误消息,例如“无效的 tw ID”... 怎么做? In ControllerAdvice add some ExceptionHandler ?ControllerAdvice添加一些ExceptionHandler

For your particular use case, you can use @ExceptionHandler in the Controller or in a @ControllerAdvice class as shown here.对于您的特定用例,您可以在 Controller 或@ControllerAdvice class 中使用@ExceptionHandler ,如此处所示。 For example, I am returning NOT_FOUND error for the sake of it.例如,我为此返回 NOT_FOUND 错误。

@ExceptionHandler({MethodArgumentTypeMismatchException.class})
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "this is the reason")
public void handle() {
}

You may not see the reason in the actual error response, until you enable在您启用之前,您可能看不到实际错误响应中的reason

server:
  error:
    include-message: always

If you think your @ExceptionHandler is only needed in a Controller class you can keep the method inside the controller.如果您认为您的@ExceptionHandler仅在 Controller class 中需要,您可以将该方法保留在 controller 中。 Alternatively you can create a @ControllerAdvice class and put the method there, so that you can reuse across multiple controllers in your application.或者,您可以创建一个@ControllerAdvice class 并将该方法放在那里,以便您可以在应用程序中的多个控制器之间重用。


However, if you want a more complex validation, I will suggest to keep the id type to String and then cast manually into Long and perform the validation.但是,如果您想要更复杂的验证,我建议将id类型保留为 String,然后手动转换为 Long 并执行验证。 Doing so you can throw your own RuntimeException and handle different cases.这样做您可以抛出自己的 RuntimeException 并处理不同的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM