Skip to content

Instantly share code, notes, and snippets.

@jeorfevre
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeorfevre/9fb2c447a01bcc724998 to your computer and use it in GitHub Desktop.
Save jeorfevre/9fb2c447a01bcc724998 to your computer and use it in GitHub Desktop.
Jersey Throws an Exception that contains a Response or other things - http://stackoverflow.com/posts/30125101 - This code is compiling and working with Jersey 2.17 & java 7
//add this code in your app.java
register(_MagicMapper.class);
package com.rizze.sof;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
* www.rizze.com
* @author je@rizze.com
*
*/
public class _MagicException extends WebApplicationException{
private static final long serialVersionUID = 7946813589876270746L;
private Response response=null;
public _MagicException(){
response=Response.ok().entity("empty").build();
}
public _MagicException(Response resp){
response =resp;
//do the stuff you like here
}
//SETTER + GETTER
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
}
package com.rizze.sof;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.apache.log4j.Logger;
/**
* www.rizze.com
* @author je@rizze.com
*
*/
@Provider
public class _MagicMapper implements ExceptionMapper<_MagicException> {
private static Logger logger = Logger.getLogger(_MagicError.class);
@Context HttpServletRequest request;
@Override
public Response toResponse(_MagicException magic){
logger.info(magic.getResponse().readEntity(String.class));
//TODO write all your code here & return what you want!
return magic.getResponse();
}
}
/**
* www.rizze.com
* @author je@rizze.com
*
*/
//Add this code in your ressource
@GET
@Path("/magic")
@Produces({"application/json"})
public Response magic() {
throw new _MagicException(Response.status(404).entity("not found").build());
}
@jeorfevre
Copy link
Author

throw a MagicException and will be catched by MagicMapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment