小编Abh*_*dav的帖子

如何在 Spring Boot 中为枚举类型返回正确的验证错误?

我创建了一个演示 Spring Boot 应用程序。该请求接受一个汽车对象并返回该对象。如果 carType 不是有效的枚举,我正在尝试找出一种向用户发送正确消息的方法。

要求

{
    "carType": "l"
}
Run Code Online (Sandbox Code Playgroud)

回复

{
    "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"
}
Run Code Online (Sandbox Code Playgroud)

如何在不显示类名和堆栈跟踪的情况下向用户发送正确的消息?我希望用户知道枚举的有效类型是什么,但不希望消息有 java 错误跟踪。有没有办法提取只有错误字段的正确消息。验证枚举的标准方法是什么?

汽车.java

import …
Run Code Online (Sandbox Code Playgroud)

java enums spring hibernate spring-boot

5
推荐指数
1
解决办法
2万
查看次数

标签 统计

enums ×1

hibernate ×1

java ×1

spring ×1

spring-boot ×1