I'm having problems handling exceptions in my RESTful service:
@Path("/blah") @Stateless public class BlahResource { @EJB BlahService blahService; @GET public Response getBlah() { try { Blah blah = blahService.getBlah(); SomeUtil.doSomething(); return blah; } catch (Exception e) { throw new RestException(e.getMessage(), "unknown reason", Response.Status.INTERNAL_SERVER_ERROR); } } }
RestException is the thrown exception:
public class RestException extends RuntimeException { private static final long serialVersionUID = 1L; private String reason; private Status status; public RestException(String message, String reason, Status status) { super(message); this.reason = reason; this.status = status; } }
And here is the exception mapping block for RestException:
@Provider public class RestExceptionMapper implements ExceptionMapper<RestException> { public Response toResponse(RestException e) { return Response.status(e.getStatus()) .entity(getExceptionString(e.getMessage(), e.getReason())) .type("application/json") .build(); } public String getExceptionString(String message, String reason) { JSONObject json = new JSONObject(); try { json.put("error", message); json.put("reason", reason); } catch (JSONException je) {} return json.toString(); } }
Now itβs important for me to provide both the response code and some response text to the end user. However, when a RestException is thrown, it throws an EJBException (with the message "EJB" an unexpected (not declared) exception is thrown ... "), and the servlet returns the response code to the client (and not the response text that I set in RestException).
This works flawlessly when my RESTful resource is not an EJB ... any ideas? I am working on this watch and I have all the ideas.
Thanks!
source share