Hi,
Just for your information. We create XXXExceptionMapper class which implements
javax.ws.rs.ext.ExceptionMapper and add it into <jaxrs:providers>, for example,
<jaxrs:server id="registryService" address="/registry/lookup">
<jaxrs:serviceBeans>
<ref component-id="registryLookupService" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean
class="org.talend.esb.registry.service.lookup.RegistryExceptionMapper" />
</jaxrs:providers>
</jaxrs:server>
In case bad parameter value, the exception (e.g. IllegalParameterException)
should be thrown, then the XXXExceptionMapper will create Response accordingly.
Regards.
Xilai
-----Original Message-----
From: Raul Acevedo [mailto:[email protected]]
Sent: Thursday, April 10, 2014 3:05 AM
To: [email protected]
Subject: customize error messages for bad input requests
Hello,
I'm using CXF 2.7.5 for some REST APIs, most of which return JSON. I'd like to
return a nice custom error message that tells the user calling the API what
fields failed when the user provides bad input; e.g.
passing in a string for an Integer parameter. Essentially I'd like to intercept
input error handling (either by type conversion or bean
validation) and tell the user: "here are the input fields that I didn't
understand", rather than a blank page with a 404.
The whole point is to avoid having API arguments all be strings that we have to
manually convert to their native types, catch exception, and creating the nice
error message. I.e. I don't want to do:
@GET @PATH("/{foo}/{bar}")
public Response foo(@PathParam("foo") Integer foo,
@PathParam("bar") Integer bar) {
List<String> failedInputNames = new ArrayList<String>();
if (cannotParseInt(foo)) failedInputNames.add("foo");
if (cannotParseInt(bar)) failedInputNames.add("bar");
if (!failedInputNames.isEmpty() {
return Response.status(NOT_FOUND, "there was an input error with
these fields: " + failedInputNames);
}
... do stuff ...
}
I would like to automate this so it automagically happens for all our API
endpoints; if any inputs cannot be bound, or fail bean validation (e.g.
@Pattern or @NotNull), the API endpoint code remains simple and
clean:
@GET @PATH("/{foo}/{bar}")
public Response foo(@PathParam("foo") Integer foo,
@PathParam("bar") Integer bar) {
... do stuff ...
}
In Spring this is possible by adding a BindingResult argument to the method; if
it's present, Spring doesn't throw an exception, but tells you via
BindingResult which input fields failed, and why. This makes it very easy to
write custom code to tell the user in a friendly way what input failed.
Is something like this possible via CXF? It's not obvious to me that CXF will
generate a consistent Exception type I can intercept.
Thanks,
Raul