Return 400 Bad Request when request body converter returns incompatible type - #2562
BabalolaBrainiac wants to merge 1 commit into
Conversation
8cd6da9 to
a6390d9
Compare
…le type. When text/uri-list is posted to a non-association endpoint, UriListHttpMessageConverter returns a CollectionModel instead of the target domain type. The argument resolver then fails with an internal exception mapped to 500. This change validates the converter output type and throws HttpMessageNotReadableException (400) instead. Fixes spring-projects#1194 Signed-off-by: Babalola Opeyemi Daniel <babalolaopedaniel@gmail.com>
a6390d9 to
8c56fec
Compare
b048a81 to
fae77f2
Compare
| if (!domainType.isInstance(newObject)) { | ||
| throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, domainType), request); | ||
| } | ||
|
|
There was a problem hiding this comment.
This and the previous check throw the same exception with the same message. They could be combined into a single guard:
if (newObject == null || !domainType.isInstance(newObject)) {
throw new HttpMessageNotReadableException(String.format(ERROR_MESSAGE, domainType), request);
}Also, the error message doesn't distinguish the type mismatch from a null result:
ERROR_MESSAGE = "Could not read an object of type %s from the request" is used for both the null case and the type mismatch case. For the type mismatch, a more informative message would help API consumers diagnose the problem, e.g.:
"Expected an object of type %s but the request body was interpreted as %s. Check the Content-Type header."This is especially useful when the client sends text/uri-list to a non-association endpoint — the current message gives no hint about what went wrong.
|
|
||
| doReturn(CollectionModel.empty()).when(converter).read(Mockito.any(Class.class), Mockito.any(HttpInputMessage.class)); | ||
|
|
||
| assertThatExceptionOfType(HttpMessageNotReadableException.class).isThrownBy(() -> { |
There was a problem hiding this comment.
Add .withMessageContaining(...) to the test assertion for precision.
The test only asserts that HttpMessageNotReadableException is thrown, but doesn't verify the message content. While this is acceptable for a minimal test, asserting .withMessageContaining(...) would make the test more precise and guard against accidentally catching a different HttpMessageNotReadableException thrown earlier in the call chain.
Fixes #1194.
|
When
text/uri-listis posted to a non-association endpoint,UriListHttpMessageConverterreturns aCollectionModelof links. The argument resolver then fails with an internal exception mapped to 500.This change validates the converter output type and throws
HttpMessageNotReadableException(400) instead.PersistentEntityResourceHandlerMethodArgumentResolverrejectsRequestBodyIfConverterReturnsIncompatibleType