Skip to content

Instantly share code, notes, and snippets.

@loinguyenduc101
Created November 24, 2015 17:57
Show Gist options
  • Save loinguyenduc101/4c94218612da99a184c6 to your computer and use it in GitHub Desktop.
Save loinguyenduc101/4c94218612da99a184c6 to your computer and use it in GitHub Desktop.
/**
*
* @author loind
*
*/
@Provider
public class JerseyDefaultExceptionMapper implements ExceptionMapper<Throwable> {
private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionMapper.class);
public static final List<Class> ignoreExceptions = new ArrayList<>();
static {
ignoreExceptions.add(NotSupportedException.class);
}
public Response toResponse(Throwable ex) {
ResponseData response = ResponseData.responseData(getHttpStatus(ex));
if(logger.isWarnEnabled() && !ignoreExceptions.contains(ex.getClass())){
StringWriter errorStackTrace = new StringWriter();
ex.printStackTrace(new PrintWriter(errorStackTrace));
logger.warn("Opos ! {}",errorStackTrace.toString());
}
return Response.ok()
.entity(response).type(MediaType.APPLICATION_JSON_TYPE)
.build();
}
private int getHttpStatus(Throwable ex) {
if(ex instanceof WebApplicationException ) { //NICE way to combine both of methods, say it in the blog
return ((WebApplicationException)ex).getResponse().getStatus();
} else {
return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(); //defaults to internal server error 500
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment