JAX-RS and EJB exception handling

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!

+6
source share
2 answers

The problem seems to be related to the EJB Exception Handling. By specification, any system exception (that is, any RuntimeException that is not specifically marked as an application exception) that is thrown from a managed bean will be packaged into an EJBException and later, if necessary, into a RemoteException thrown to the client. This is the situation you seem to be in, and to avoid this, you can:

  • throw your RestException into a checked exception and handle it as such
  • use the @ApplicationException annotation for your RestException
  • create an EJBExceptionMapper and extract information from (RestfulException) e.getCause()
+5
source

A similar case works for me when RestException extends javax.ws.rs.WebApplicationException

0
source

Source: https://habr.com/ru/post/893961/


All Articles