简体   繁体   English

Spring 引导请求正文验证在输入无效数据类型时添加自定义消息

[英]Spring Boot request body validation add customize messages when input an invalid data type

I am using Spring Boot to create a POST request and I need to validate the request body based on user inputs.我正在使用 Spring Boot 创建 POST 请求,我需要根据用户输入验证请求正文。 However, when the user inputS an invalid data type, the response shows nothing, just 400 bad request status.但是,当用户输入一个无效的数据类型时,响应什么也没有显示,只是400 bad request status。 Can I add a message to show the user which field is an invalid data type?我可以添加一条消息来向用户显示哪个字段是无效数据类型吗?

For example: Here is my controller:例如:这是我的 controller:

@RestController
@RequestMapping("/api/foo")
public class FooController {

  @PostMapping("/save")
  public void postFoo(@Valid @RequestBody Foo foo) {
    // do somethings
  }
}

And here is my Foo class:这是我的 Foo class:

public class Foo {
  @NotBlank
  private String name;
  private Integer age;

  // getter/setter
}

So now I post a request as below:所以现在我发布如下请求:

{
  "name": "Foo Name",
  "age": "A String"
}

The server will respond with the status 400 Bad request without any message.服务器将响应状态400 Bad request而没有任何消息。 How can I put my message such as Age must be an integer .我怎样才能把我的消息,例如Age must be an integer

Until now I only have a solution that changes Age to String and adds a @Pattern validation annotation.到目前为止,我只有一个将 Age 更改为 String 并添加 @Pattern 验证注释的解决方案。

public class Foo {
  @NotBlank
  private String name;
  @Pattern(regexp = "[0-9]*", message = "Age must be an intege")
  private String age;

  // getter/setter
}

In your post method signature, you can make use of Response Entity class to show some exception message that is to be returned to the user, along with some status code.在您的 post 方法签名中,您可以使用响应实体 class 来显示一些要返回给用户的异常消息以及一些状态代码。

You need to implement error handling mechanism.您需要实现错误处理机制。

In your error handler you need to catch all exceptions and return error response.在您的错误处理程序中,您需要捕获所有异常并返回错误响应。 Here is an example based on Controller level ExceptionHandling下面是一个基于 Controller 级别 ExceptionHandling 的示例

public class FooController{

   //...
   @ResponseStatus(value=HttpStatus.BAD_REQUEST)
   @ExceptionHandler({ CustomException1.class, CustomException2.class })
      public ErrorResponse handleException() {
      //
   }
}

Here in ErrorResponse model you can set error code and message according to exception and via ResponseStatus you can assign http errro code在 ErrorResponse model 中,您可以根据异常设置错误代码和消息,通过 ResponseStatus 您可以分配 http 错误代码

However this his approach has a major drawback: The @ExceptionHandler annotated method is only active for that particular Controller, not globally for the entire application.然而,他的方法有一个主要缺点:@ExceptionHandler 注释方法仅对特定的 Controller 有效,而不是对整个应用程序全局有效。

To globally handle exception you can use ControllerAdvice.要全局处理异常,您可以使用 ControllerAdvice。 Here is a good article on overall error handling mechanism 是一篇关于整体错误处理机制的好文章

Replacing @NotBlank with @NotBlank(message = "Age must be an integer") will solve your issue.@NotBlank @NotBlank(message = "Age must be an integer")替换 @NotBlank 将解决您的问题。

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

相关问题 Spring 引导 - 也为参数 TYPE 请求正文验证 - Spring Boot - request body validation also for parameter TYPE Spring 启动应用程序中的请求正文验证失败 - Request body validation in Spring boot application Fails Spring 引导中请求正文的默认类型是什么 - What is the default type of request body in Spring boot 如何在请求正文中指定订单验证 Spring 启动 Rest Controller - How to specify order validation in Request body Spring Boot Rest Controller Spring 在用于不同 API 的相同 DTO 上的启动请求正文验证 - Spring Boot Request body validation on same DTO used for different API 将字符串数据类型限制为仅用于 Spring 引导 2.4 (Jackson) 中的请求正文的字符串类型 - Restrict string data type to only string types for request body in Spring boot 2.4 (Jackson) 自定义正文错误消息 - Spring启动REST - Customize body error message - Spring boot REST Spring Boot在错误响应实体中添加请求主体 - Spring Boot add Request Body in the Error Response Entity 为什么我无法在 Swagger UI 中为使用 Spring 引导创建的端点自定义请求正文? - Why I am unable to customize Request Body in Swagger UI for an endpoint that I created using Spring Boot? 在 Java Spring 启动中解析请求体数据成 object - Parsing request body data into object in Java Spring boot
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM