I'm learning JAX-RS (aka, JSR-311) using Jersey. I've successfuly created a Root Resource and am playing around with parameters:
@Path("/hello")
public class HelloWorldResource {
@GET
@Produces("text/html")
public String get(
@QueryParam("name") String name,
@QueryParam("birthDate") Date birthDate) {
// Return a greeting with the name and age
}
}
This works great, and handles any format in the current locale which is understood by the Date(String) constructor (like YYYY/mm/dd and mm/dd/YYYY). But if I supply a value which is invalid or not understood, I get a 404 response.
For example:
GET /hello?name=Mark&birthDate=X
404 Not Found
How can I customize this behavior? Maybe a different response code (probably "400 Bad Request")? What about logging an error? Maybe add a description of the problem ("bad date format") in a custom header to aid troubleshooting? Or return a whole Error response with details, along with a 5xx status code?
I too like StaxMan would probably implement that QueryParam as a String, then handle the conversion, rethrowing as necessary.
If the locale specific behavior is the desired and expected behavior, you would use the following to return the 400 BAD REQUEST error:
throw new WebApplicationException(Response.Status.BAD_REQUEST);
See the JavaDoc for javax.ws.rs.core.Response.Status for more options.
Create above class. This will handle 404 (NotFoundException) and here in toResponse method you can give your custom response. Similarly there are ParamException etc. which you would need to map to provide customized responses.