Java Reference
In-Depth Information
@GET
public Response doGet() throws FileNotFoundException {
//build entity from file
File file = new File("/path/doesnt/exist/file.txt");
if( !file.exists() ) {
System.out.println("Couln't find file.");
throw new FileNotFoundException("My custom message.");
}
Response response = Response.ok(file).build();
System.out.println("Returning exception response.");
return response;
}
}
In this example, you have a regular method that looks for a file on the server and, if it isn't
found, throws a standard java.io.FileNotFoundException . This is a checked exception, so
you declare it in the throws clause on the method. Because the path specified doesn't exist,
invoking the service will throw this exception, and the Response.ok will never be built. In-
stead, the JAX-RS runtime will look in its list of provider implementations and attempt to map
the exception to a suitable mapping implementation.
If an exception mapping provider can be found that matches the exact exception thrown or
one of its superclasses, then JAX-RS will take the exception mapping provider implementa-
tion that represents the nearest match to the runtime type of the exception and use that to build
the response.
NOTE
If an exception is thrown during an attempt to put together a response inside an exception mapping
implementation, the runtime will return a 500 Internal Server Error to the client.
Example 8-32 shows how FileNotFoundExceptionMapper implementation builds a 404 re-
sponse with a custom message.
Example8-32.FileNotFoundExceptionMapper.java
package com.soacookbook.rest.except;
import java.io.FileNotFoundException;
Search WWH ::




Custom Search