【发布时间】:2020-10-25 15:52:37
【问题描述】:
我正在使用spring-boot version:2.0.5
分级:
buildscript {
ext {
springBootVersion = '2.0.5.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'io.reflectoring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 11
repositories {
mavenCentral()
}
dependencies {
implementation('org.springframework.boot:spring-boot-starter-data-jpa')
implementation('org.springframework.boot:spring-boot-starter-validation')
implementation('org.springframework.boot:spring-boot-starter-web')
runtimeOnly('com.h2database:h2')
testImplementation('org.springframework.boot:spring-boot-starter-test')
testImplementation('org.junit.jupiter:junit-jupiter-engine:5.0.1')
// these dependencies are needed when running with Java 11, since they
// are no longer part of the JDK
implementation('javax.xml.bind:jaxb-api:2.3.1')
implementation('org.javassist:javassist:3.23.1-GA')
}
test{
useJUnitPlatform()
}
控制器
@RestController
class ValidateRequestBodyController {
@PostMapping("/validateBody")
ResponseEntity<String> validateBody(@Valid @RequestBody Input input) {
return ResponseEntity.ok("valid");
}
}
验证器类
class InputWithCustomValidator {
@IpAddress
private String ipAddress;
// ...
}
class IpAddressValidator implements ConstraintValidator<IpAddress, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
Pattern pattern =
Pattern.compile("^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$");
Matcher matcher = pattern.matcher(value);
//step 1
if (!matcher.matches()) {
return 400;
}
//Step 2
if (ipAddress already in DB) {
return 409; //conflict with other IP address
}
//Also I need to return different exception based on diff validations
}
}
控制器建议
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ErrorResponse> handle(ValidationException e) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
return ResponseEntity
.status(HttpStatus.BAD_REQUEST)
.body(e.getMessage());
}
如果我从验证器中抛出 customException,那么即使我有相应的 controllerAdvice,我也会收到以下错误消息,
{
"code": "invalid_request"
"description": "HV000028: Unexpected exception during isValid call."
}
总是,我收到 400 Bad request,因为我有一个总是返回 400 的 controllerAdvice。
我想在这里实现的是,是否有可能返回带有状态代码的 customException,或者是否有可能从验证器返回不同的状态代码?我在 StackOverflow 中看到了类似的帖子,但没有答案。我还查看了其他帖子,但我发现它没有用。
【问题讨论】:
-
-
我试过了......但没有用......让我更新问题给你
-
@dotore 我已经更新了这个问题。如果我返回自定义异常,那么我曾经收到上述错误消息。似乎 spring-validator 吞下了自定义异常并抛出 ValidationException
标签: java spring spring-boot spring-validator