Shawn Strickland Shawn Strickland - 6 months ago 42
JSON Question

Non-Jersey JAX-RS Custom Exception with Status Code

I'm using Apache Wink with JAX-RS, and I'm working on throwing custom exceptions for error handling. I was able to get something working far enough to send back a custom JSON message with a status code, but I'd like the ability to use this custom Exception for more than just one type of Response (in this case,

Status.BAD_REQUEST
). How can I inject a status code into my exception so that I can throw more than one type of status with the custom error message?

JAX-RS Resource

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response memberRegistration(
JSONObject json,
@HeaderParam("Client-ID") String clientId,
@HeaderParam("Client-Secret") String clientSecret) throws WebApplicationException, Exception {

// Authenticate the user using the credentials provided
appAuth.checkClientId(clientId, clientSecret);
if (!"new".equals(json.get("type_of_membership"))) {
throw new WebApplicationException("Type of membership (new) is not correct for this route.");
}
return Response.ok(json, MediaType.APPLICATION_JSON).build();

}


Custom Exception

public class WebApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
public WebApplicationException() {
super();
}
public WebApplicationException(String msg) {
super(msg);
}
public WebApplicationException(String msg, Exception e) {
super(msg, e);
}
}


Custom Exception Handler/ExceptionMapper implementation

@Provider
public class WebApplicationExceptionHandler implements ExceptionMapper<WebApplicationException>
{
@Override
public Response toResponse(WebApplicationException exception)
{
JSONObject json = new JSONObject();
json.put("message", exception.getMessage());
return Response.status(Status.BAD_REQUEST).entity(json.toString()).build();
}
}

Answer

I don't know if I got your question, but I could suggest that adding an instance variable to your custom exception to hold the status code that you want, you can do that as follow:

public class WebApplicationException extends Exception implements Serializable
{
private static final long serialVersionUID = 1L;
private Response.Status status = Response.Status.BAD_REQUEST;

public WebApplicationException() {
    super();
}
public WebApplicationException(String msg) {
    super(msg);
}
public WebApplicationException(String msg, Exception e)  {
    super(msg, e);
}

public WebApplicationException(String msg, Response.Status status) {
    super(msg);
    this.status = status;
}
public WebApplicationException(String msg, Exception e, Response.Status status)  {
    super(msg, e);
    this.status = status;
}

public Response.Status getStatus() {
     return status;
}
}

then you can modify the return statement in "WebApplicationExceptionHandler" as

return Response.status(exception.getStatus()).entity(json.toString()).build();