Как избежать броски httpmessageConversionException, связанные с классами, связанные с веснойJAVA

Программисты JAVA общаются здесь
Anonymous
Как избежать броски httpmessageConversionException, связанные с классами, связанные с весной

Сообщение Anonymous »

Я пробую программы, ориентированное на данные, используя Java 21 весной. Я создал образец класса с проверкой данных, как SO: < /p>

Код: Выделить всё

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type",
visible = true
)
@JsonSubTypes({
@JsonSubTypes.Type(value = User.RegularUser.class, name = "regular"),
})
public sealed interface User {
record RegularUser(String id, String name, String type) implements User {
public RegularUser {
if (id == null || id.trim().isEmpty()) {
throw new IllegalArgumentException("User id cannot be null or empty.");
}
}
}
}
< /code>
и мой контроллер REST, как и ExceptionHandler, пытаясь поймать исключение, брошенное из пользователя: < /p>
@ExceptionHandler({HttpMessageConversionException.class})
public String badRequestHandler(Exception ex) {
log.info("Here");
log.error(ex.getMessage(), ex);
return ex.getMessage();
}

@ExceptionHandler({IllegalArgumentException.class})
public String handler(Exception ex) {
log.info("There");
log.error(ex.getMessage(), ex);
return ex.getMessage();
}

@PostMapping("/user")
public String logUser(@RequestBody User user) {
log.info("{}", user);
return user.toString();
}
< /code>
curl --insecure -X POST 'http://localhost:8080/user' --header 'Content-Type: application/json' --data '{"name": "dave", "id": "", "type": "regular"}'

Выход:
2025-08-11 10:43:57.371 INFO 15150 [nio-8080-exec-1] c.o.s.w.r.SampleRestController : Here
2025-08-11 10:43:57.371 ERROR 15150 [nio-8080-exec-1] c.o.s.w.r.SampleRestController : JSON parse error: Cannot construct instance of `com.org.sample.model.User$RegularUser`, problem: User id cannot be null or empty.
< /code>
This seems rather unintuitive, as I would like to catch the specific exception thrown, and not have to go through the causes of the exception in the exception handler to find my specific exception. How can I avoid throwing the HttpMessageConversion exception, and just have the ExceptionHandler catch my thrown Exception instead?
I have also tried the following:
@PostMapping("/user")
public String logUser(@RequestBody Map userMap) {
log.info("Before: {}", userMap);
var user = objectMapper.convertValue(userMap, User.class);
log.info("After: {}", user);
return user.toString();
}
< /code>
This did not work either as it would still throw IllegalArgumentException caused by ValueInstantiationException caused by my thrown exception. (Although this catches IllegalArgumentException, it does not catch 'my' thrown exception, and if I change to throwing a custom Exception like making a UserCreationException class, it would fail)
edit: This did work, considering that type will unavoidably throw an InvalidTypeIdException due to the requirement for type to be present to handle polymorphic types with Jackson. When handling other fields other than type, it worked.

Подробнее здесь: https://stackoverflow.com/questions/797 ... -in-spring

Вернуться в «JAVA»