gpt4 book ai didi

java - 将 HTTP 请求数据转换为枚举时捕获异常

转载 作者:太空宇宙 更新时间:2023-11-04 10:24:13 30 4
gpt4 key购买 nike

使用自定义 com.fasterxml.jackson.databind.JsonDeserializer 反序列化器实现将 HTTP 请求值反序列化为枚举时遇到问题:

public class EnvelopeColorJsonDeserializer extends JsonDeserializer<EnvelopeColor> {

@Override
public EnvelopeColor deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String val = p.getValueAsString();
return EnvelopeColor.fromCode(val);
}
}

这就是我将值转换为枚举的方法:

public static EnvelopeColor fromCode(String code) {
Assert.notNull(code, "code");
for (EnvelopeColor type : values()) {
if (code.equals(type.code)) {
return type;
}
}
throw new RuntimeException("Not supported color: " + code);
}

端点:

@PostMapping("/")
public @ResponseBody
ResponseEntity add(@RequestBody EnvelopeDto envelope) {
// some stuff goes here...
}

问题

是否有某种方法可以a)在进入反序列化过程之前检查HTTP请求值是否是有效的枚举常量值或b)如何在@ControllerAdvice异常处理程序中捕获异常? (我想避免在 fromCode() 方法中抛出自定义异常)。

最佳答案

您可以为 HttpMessageNotReadableException 类添加异常处理程序。当 Spring 无法将有效负载反序列化到 DTO 中时,会引发此异常。

@ExceptionHandler(org.springframework.http.converter.HttpMessageNotReadableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
protected @ResponseBody handleIncorrectData(HttpMessageNotReadableException ex,
HttpServletRequest request, HttpServletResponse response){

....

}

此外,您可以定义一个自定义EnumConverter,它将向用户提供正确的枚举值的确切详细信息。

public class CustomEnumConverter extends EnumConverter {

@Override
public Object unmarshal(HierarchicalStreamReader reader,
UnmarshallingContext context) {
try {
return super.unmarshal(reader, context);
} catch (IllegalArgumentException e) {
String inputValue = reader.getValue();
Class contextType = context.getRequiredType();
StringBuilder sb = new StringBuilder();
Object[] enumConstants = contextType.getEnumConstants();
for (Object o : enumConstants) {
sb.append(o + ",");
}
if (sb.length() > 0)
sb.deleteCharAt(sb.length() - 1);
throw new InvalidArgumentException(ErrorCode.INVALID_ARGUMENT, inputValue,
reader.getNodeName(), sb.toString());
}
}

}

关于java - 将 HTTP 请求数据转换为枚举时捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50735811/

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