Java Reference
In-Depth Information
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
/**
* Maps a FileNotFoundException to a 404 and uses its message
* in the response.
*/
@Provider
public class FileNotFoundExceptionMapper implements
ExceptionMapper<java.io.FileNotFoundException> {
public Response toResponse(FileNotFoundException ex) {
System.out.println("Returning mapped exception.");
return Response.status(404)
.entity(ex.getMessage())
.type("text/plain")
.build();
}
}
If you deploy and then open the service URL at http://localhost:8080/restexamples/resources/
exception in Firefox, you'll see the message indicated in the constructor of the
FileNotFoundException : “My custom message”. The response status code is still a 404, so
browsers such as IE or Chrome may display their own standard error pages. But the point of
this example is that you're getting your own message in there, and, more importantly, you're
getting to program with exceptions in the way that Java developers are accustomed to doing.
The mapping capability is also nice because the runtime loads your mapping and invokes it
automatically as necessary, keeping your implementation loosely coupled.
Search WWH ::




Custom Search