I'm having trouble 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 a mapped 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 mapper 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 is important for me to provide both a response code AND some response text to the end user. However, when a RestException is thrown, this causes an EJBException (with message "EJB threw an unexpected (non-declared) exception...") to be thrown as well, and the servlet only returns the response code to the client (and not the response text that I set in RestException).
This works flawlessly when my RESTful resource isn't an EJB... any ideas? I've been working on this for hours and I'm all out of ideas.
Thanks!
WebApplicationException. This can be thrown by application code and automatically processed by JAX-RS without having to write an explicit mapper.
It's a very common exception thrown when the BeanFactory creates beans of the bean definitions, and encounteres a problem. This article will explore the most common causes of this exception, along with the solutions.
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.
The problem seems to be connected with EJB Exception Handling. By the specification any system exception
(that is - any RuntimeException not specifically marked as Application Exception) that is thrown from within a managed bean will be packaged into an EJBException and later, if needed, into RemoteException thrown to the client. That is a situation you seem to be in, and in order to avoid that you can either:
(RestfulException) e.getCause()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With