Java Reference
In-Depth Information
request sent by the client was syntactically incorrect ().” There's no way that I'm aware of to
change that message as of the current API, and still specify the response status directly using
the WebApplicationException . You would think that something like this would do the trick:
RuntimeException re = new RuntimeException("My forbidden message...");
throw new WebApplicationException(re, 403);
But it doesn't. Your custom message is ignored, though your status code is retained (you could
also have used the Status enum here). So if you really, really want to create a more de-
scriptive response, you'll have to create another exception first, pass it into the WebApplica-
tionException instance, and just return that.
I don't recommend the following code; it doesn't allow you to specify a meaningful status
code with the exception (everything is just a 500 Internal Server Error), which is an important
part of REST. Still, it does get your message to the client:
@GET
public Response doGet(){
throw new RuntimeException("My forbidden message...");
}
The problem with this code is that it's confusing because it's lying. You're saying that the cli-
ent tried to access a forbidden resource, but you're returning a status code of 500. You may be
able to get away with such squirrelly things in the regular world of servlets and JSPs, where
any exception just returns a web page anyway, but this is a real problem in REST. Of course,
returning an entire stack trace to the client isn't exactly a best practice anyway, especially
when it's in conflict with what's ostensibly the issue:
java.lang.RuntimeException: My forbidden message...
com.soacookbook.rest.response.CustomStatusCode.doGet(CustomStatusCode.java:16)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
This is where custom exception mappers come in.
Using exception mappers
The response builder feature allows you to build responses that correspond to particular HTTP
response types, including those that represent an error state such as Not Found. But JAX-
RS also provides the WebApplicationException class as a general exception mechanism,
as Java developers may be more accustomed to using exceptions in this way during devel-
opment. If necessary, the WebApplicationException class can be extended to provide your
own message, as in the following example:
Search WWH ::




Custom Search