简体   繁体   English

自定义 spring 启动验证响应

[英]Custom spring boot validation response

I used spring-boot validation below:我在下面使用了 spring-boot 验证:

in gradle:在 gradle 中:

implementation 'org.springframework.boot:spring-boot-starter-validation'

in request:在请求中:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class ApiTransactionRequest {
    private String id;
    @NotNull
    private String transaction_id;
    @NotNull
    private String apiOperation;
    @NotNull
...

When testing this case I got these infos: Spring app show this log:在测试这个案例时,我得到了这些信息:Spring app show this log:

WARN 28840 --- [nio-8080-exec-1].wsmsDefaultHandlerExceptionResolver: Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity警告 28840 --- [nio-8080-exec-1].wsmsDefaultHandlerExceptionResolver:已解决 [org.springframework.web.bind.MethodArgumentNotValidException:公共 org.springframework.http.ResponseEntity 中参数 [0] 的验证失败

Http Response(spring boot validation response message) Http Response(spring boot验证响应消息)

{
   "timestamp": "2022-12-05T09:58:55.011+00:00",
   "status": 400,
   "error": "Bad Request",
   "path": "/transactions"
}

Actually I want to get the custom http response instead spring boot validation message, like this:实际上我想获取自定义 http 响应而不是 spring 启动验证消息,如下所示:

{
   "date": "2022-12-05",
   "status": 400.03,
   "error": "Transaction id is invalid",
   "message": "Transaction id is not null"
}

Any helps, tks任何帮助,谢谢

You need to use @ControllerAdvice and make a custom exception handling.您需要使用@ControllerAdvice并进行自定义异常处理。 Spring should thrown MethodArgumentNotValidException or ConstraintViolationException - it depends do you throw the exception from the Controller or not. Spring 应该抛出MethodArgumentNotValidExceptionConstraintViolationException - 这取决于你是否从 Controller 抛出异常。

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseEntity<MyResponse> handleException(MethodArgumentNotValidException exception) {
        String customException = exception.getBindingResult().getFieldErrors().stream()
                       .map(x -> x.getField() + x.getDefaultMessage())
                       .collect(Collectors.joining(","))

        return  ResponseEntity.badRequest().body(new MyResponse(customException);
    }

MyResponse could have the message MyResponse可能有消息

If you want a normal API Jason Request please use @Entity instead:如果您想要一个普通的 API Jason 请求,请改用@Entity

@Entity
public class ApiTransactionRequest {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO) //Add this line if you your ID will be created by the Webapp
    @NotNull
    private String id;
    @NotNull
    private String transaction_id;
    @NotNull
    private String apiOperation;
    @NotNull
// omitted input

In your Controller you will to Something like this在您的 Controller 中,您会这样

@RestController
public class UserController {

    @PostMapping("/users")
    ResponseEntity<String> addUser(@Valid @RequestBody User user) {
        // persisting the user
        return ResponseEntity.ok("User is valid");
    }
    
    // standard constructors / other methods
}

You can look it up here你可以在这里查看

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

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