[英]How to return validation message using Enum class in spring boot?
[英]How to return a proper validation error for enum types in Spring Boot?
我创建了一个演示 spring 启动应用程序。 该请求接受了一辆汽车 object 并返回了相同的。 如果 carType 不是有效枚举,我正在尝试找出一种向用户发送正确消息的方法。
要求
{
"carType": "l"
}
回复
{
"message": "JSON parse error: Cannot deserialize value of type `com.example.demo.Car$CarType` from String \"l\": not one of the values accepted for Enum class: [Racing, Sedan]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.example.demo.Car$CarType` from String \"l\": not one of the values accepted for Enum class: [Racing, Sedan]\n at [Source: (PushbackInputStream); line: 2, column: 13] (through reference chain: com.example.demo.Car[\"carType\"])",
"statusCode": "BAD_REQUEST"
}
如何在不显示 class 名称和堆栈跟踪的情况下向用户发送正确的消息? 我希望用户知道枚举的有效类型是什么,但不希望消息有 java 错误跟踪。 有没有一种方法可以提取只有错误字段的正确消息。 验证枚举的标准方法是什么?
车.java
import lombok.*;
@Getter
@Setter
public class Car {
enum CarType {
Sedan,
Racing
}
CarType carType;
}
DemoControllerAdvice.java
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class DemoControllerAdvice {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ErrorObject handleJsonErrors(HttpMessageNotReadableException exception){
return new ErrorObject(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
}
DemoController.java
@RestController
public class DemoController {
@PostMapping("/car")
public Car postMyCar(@RequestBody Car car){
return car;
}
}
有没有什么巧妙的方法可以使用 Hibernate Validator 但不使用自定义 hibernate Validator 就像下面的答案一样? 如何将 Hibernate 验证注释与枚举一起使用?
不。反序列化发生在验证之前。
如果你想让 Hibernate 这样做,那么你已经链接到答案了。 否则你将不得不自己处理异常。
private static final Pattern ENUM_MSG = Pattern.compile("values accepted for Enum class: \[([^\]])\]);"
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ErrorObject handleJsonErrors(HttpMessageNotReadableException exception){
if (exception.getCause() != null && exception.getCause() instanceof InvalidFormatException) {
Matcher match = ENUM_MSG.matcher(exception.getCause().getMessage());
if (match.test()) {
return new ErrorObject("value should be: " + match.group(1), HttpStatus.BAD_REQUEST);
}
}
return new ErrorObject(exception.getMessage(), HttpStatus.BAD_REQUEST);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.