gpt4 book ai didi

spring-boot - 如何将 ConstraintViolationException 500 错误转换为 400 错误请求?

转载 作者:行者123 更新时间:2023-12-04 09:42:03 25 4
gpt4 key购买 nike

如果我使用这样的约束 @NotNull 然后在 Controller 中

public User createUser(
@Validated
@RequestBody User user) {}

它提供了一个非常好的 400 异常细节。

但是,如果我像这样使用自己的自定义验证器:
public User createUser(
@UserConstraint
@RequestBody User user) {}

它会抛出一个 500 服务器错误,如下所示:
javax.validation.ConstraintViolationException: createUser.user: Error with field: 'test35'
at org.springframework.validation.beanvalidation.MethodValidationInterceptor.invoke(MethodValidationInterceptor.java:117) ~[spring-context-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.10.RELEASE.jar:5.1.10.RELEASE]
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69) ~[spring-security-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]

有没有办法让 400 消息得到响应?

理想情况下,400 消息应该与 Spring 的验证 JSON 相同
{
"timestamp": "2019-10-30T02:33:15.489+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"Size.user.lastName",
"Size.lastName",
"Size.java.lang.String",
"Size"
],
"arguments": [
{
"codes": [
"user.lastName",
"lastName"
],
"arguments": null,
"defaultMessage": "lastName",
"code": "lastName"
},
25,
1
],
"defaultMessage": "size must be between 1 and 25",
"objectName": "user",
"field": "lastName",
"rejectedValue": "",
"bindingFailure": false,
"code": "Size"
}
],
"message": "Validation failed for object='user'. Error count: 1",
"path": "/api/v1/users"
}

最佳答案

是的,您可以创建一个 custom error handler然后您也可以在您的回复和状态中添加任何内容。这是更改状态的简单方法:
1.- 简单的更改方法 statusConstraintViolationException被抛出。

import javax.validation.ConstraintViolationException;

@ControllerAdvice
public class CustomErrorHandler {

@ExceptionHandler(ConstraintViolationException.class)
public void handleConstraintViolationException(ConstraintViolationException exception,
ServletWebRequest webRequest) throws IOException {
webRequest.getResponse().sendError(HttpStatus.BAD_REQUEST.value(), exception.getMessage());
}
}
2.- 在 ConstraintViolationException 时放置响应的自定义方式发生。
@ControllerAdvice
public class CustomErrorHandler {

@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<CustomError> handleConstraintViolationException(ConstraintViolationException exception) {
CustomError customError = new CustomError();
customError.setStatus(HttpStatus.BAD_REQUEST);
customError.setMessage(exception.getMessage());
customError.addConstraintErrors(exception.getConstraintViolations());
return ResponseEntity.badRequest().body(customError);
}
}

关于spring-boot - 如何将 ConstraintViolationException 500 错误转换为 400 错误请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58614373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com