I defined a datatype and its API:
public class DataType {
@Column
private String name;
}
// API is:
public class DataTypeAPI {
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ManagedAsync
public void createDataType(
final DataType dataType,
) {
...
asyncResponse.resume(Response.status(Response.Status.CREATED)
.entity(dataType)
.build());
}
}
Everything is fine if I posed
{
"name": "xxx"
}
,
but when I posted { "name1": "xxx" }
, I got the following text/plain
response:
Unrecognized field "name1" (class com.xxx.datatypes.DataType), not marked as ignorable (1 known properties: "name"])
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@526e34b1; line: 2, column: 15] (through reference chain: com.xxx.datatypes.DataType["name1"])
I prefer to convert the above error into JSON response. but event I added the following exception mapper, it is not returning JSON response.
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable ex) {
System.out.println("GenericExceptionMapper");
ex.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorBody(500, ex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
Why my above exception mapper cannot catch the jersey parsing error. Could someone explain it to me? Thanks
UPDATE
I have two questions:
1, how to make the response to be application/json
instead of text/plain
?
2, why my exception mapper did not catch the exception raised and map it to a json response?
UPDATE
I added the following mapper:
public class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
public Response toResponse(JsonMappingException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ErrorBody(500, ex.getMessage()))
.type(MediaType.APPLICATION_JSON)
.build();
}
}
Now, I can get the json response:
{
"code": 500,
"message": "Unrecognized field \"name1\" (class com.xxx.datatypes.DataType), not marked as ignorable (1 known properties: \"name\"])\n at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@1d8cd12a; line: 2, column: 15] (through reference chain: class com.xxx.datatypes.DataType[\"name1\"])"
}
I still have two questions:
1, why my generic exception mapper cannot catch it.
2, The json mapping exception mapper cannot map the following exception Unexpected character ('}' (code 125)): was expecting double-quote to start field name
at [Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@7615743c; line: 3, column: 2]
when {"name": "xxxx",}
posted (comma , added for testing)
JsonParseException
in mapper, it is not working. so, I am confused. – Silica