定制 Spring Boot 验证响应

wecizke3  于 2022-12-13  发布在  Spring
关注(0)|答案(2)|浏览(159)

我使用了下面的Spring启动验证:
分级:

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

在请求中:

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
...

在测试此案例时,我获得了以下信息:Spring应用程序显示此日志:
警告28840 --- [nio-8080-exec-1] .w.s.m.s.默认处理程序异常解析程序:已解决[org.springframework.web.bind.方法参数无效异常:验证公共组织.springframework.http.ResponseEntity中的参数[0]失败
Http响应( Spring Boot 验证响应消息)

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

实际上,我希望获得自定义http响应,而不是spring Boot 验证消息,如下所示:

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

有什么帮助吗,谢谢

jjhzyzn0

jjhzyzn01#

你需要使用@ControllerAdvice并进行自定义异常处理。Spring应该抛出MethodArgumentNotValidExceptionConstraintViolationException-这取决于你是否从控制器抛出异常。

@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可能有消息

s8vozzvw

s8vozzvw2#

如果您需要普通的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

在你的控制器里你会看到这样的东西

@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
}

你可以查一下here

相关问题