Java Reference
In-Depth Information
public class MyException extends WebApplicationException {
//creates a custom 404 Not Found exception
public MyException() {
super(Responses.notFound().build());
}
//msg represents the entity of the 404 response
public MyException(String msg) {
super(Response.status(Responses.NOT_FOUND).
entity(msg).type("text/plain").build());
}
}
Alternatively, you might find use for the web exception mapping feature. If there's an existing
exception that you want to throw, you can use the ExceptionMapper interface. First, you an-
notate the mapper implementation with @Provider so that the JAX-RS runtime will pick it
up. When a resource throws an exception that the runtime has a mapping for, it uses the ex-
ception provider (in the case of the next example, FileNotFoundExceptionMapper ) to get its
response, which you can build however you like. The response is processed as if the method
in your service that threw the checked or runtime exception had instead returned the response
built by the mapping implementation.
Example 8-31 illustrates a service that uses the exception mapping facility. The example
simply throws a FileNotFoundException in order to demonstrate the execution mapping
capability.
Example8-31.ExceptionService.java
package com.soacookbook.rest.except;
import java.io.File;
import java.io.FileNotFoundException;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
/**
* Purposefully throws an exception in order to demonstrate
* the Exception mapping capability.
*/
@Path("exception")
public class ExceptionService {
Search WWH ::




Custom Search