Return 5xx HTTP status for invalid target types with Jackson

InvalidDefinitionException has been introduced in Jackson 2.9 to be
able to differentiate invalid data sent from the client (should still
generate a 4xx HTTP status code) from server side errors like beans with
no default constructor (should generate a 5xx HTTP status code).

Issue: SPR-14925
This commit is contained in:
Sebastien Deleuze
2017-04-05 10:36:01 +02:00
parent 454e61e8ac
commit ed8565894a
5 changed files with 85 additions and 1 deletions

View File

@@ -31,9 +31,11 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.MockHttpInputMessage;
import org.springframework.http.MockHttpOutputMessage;
@@ -380,6 +382,22 @@ public class MappingJackson2HttpMessageConverterTests {
assertTrue(result.contains("\"number\":123"));
}
@Test
public void readWithNoDefaultConstructor() throws Exception {
String body = "{\"property1\":\"foo\",\"property2\":\"bar\"}";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
try {
converter.read(BeanWithNoDefaultConstructor.class, inputMessage);
}
catch (HttpMessageNotReadableException ex) {
assertTrue(ex.getErrorStatus().isPresent());
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, ex.getErrorStatus().get());
return;
}
fail();
}
interface MyInterface {
@@ -537,4 +555,25 @@ public class MappingJackson2HttpMessageConverterTests {
}
}
private static class BeanWithNoDefaultConstructor {
private final String property1;
private final String property2;
public BeanWithNoDefaultConstructor(String property1, String property2) {
this.property1 = property1;
this.property2 = property2;
}
public String getProperty1() {
return property1;
}
public String getProperty2() {
return property2;
}
}
}