Как избежать броски 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)

Подробнее здесь: https://stackoverflow.com/questions/797 ... -in-spring
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

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