@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是映射例外:
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;
}
}
這裏是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();
}
}
現在,對我來說最重要的是提供響應代碼和一些響應文本u SER。但是,當引發RestException時,這會導致EJBException(帶有消息「EJB拋出一個意外的(未聲明的)異常...」),並且該servlet僅將響應代碼返回給客戶端(以及而不是我在RestException中設置的響應文本)。
當我的RESTful資源不是EJB時,這完美地工作......任何想法?我一直在爲此工作數小時,而且我都沒有想法。
謝謝!
我有一個類似的用例,我的EJB引發了WebApplicationException並且它可以工作。 – lili