我有一个POJO,其中一个字段使用hibernate映射:
@Enumerated(EnumType.STRING)
@Column(name = "status")
private UserStatus status;枚举只有两个可能的值:激活和停用
在我的控制器中,我有一个在数据库中保存实体的简单方法:
@PostMapping("/save")
private UserDto saveUser(@RequestBody User user){
return userService.save(user);
}如果我尝试使用不存在的UserStatus保存用户,则会收到以下错误消息:
"message": "JSON parse error: Cannot deserialize value of type `com.example.demo.utils.UserStatus` from String \"Deactivated1\": value not one of declared Enum instance names: [Deactivated, Activated]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.example.demo.utils.UserStatus` from String \"Deactivated1\": value not one of declared Enum instance names: [Deactivated, Activated]\n at [Source: (PushbackInputStream); line: 3, column: 12] (through reference chain: com.example.demo.entity.User[\"status\"])",如何处理不存在的值的序列化?在这种情况下,我想抛出一个自定义异常。谢谢!
发布于 2019-06-13 04:29:31
您可以在您的控制器中添加一个ExceptionHandler,如下所示
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity handleException() {
// create custom error response
}`或者,如果您希望在一般情况下处理这种情况,那么对于所有控制器,您都可以使用ControllerAdvice。
https://stackoverflow.com/questions/56569710
复制相似问题