我在我的RESTful服务中处理异常遇到了困难:
@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();
}
}
现在,对于最终用户来说,我提供响应代码和一些响应文本是很重要的。但是,当抛出RestException时,这会导致EJBException(带有消息“EJB抛出了意外(未声明)异常…”)也被抛出,而Servlet仅向客户端返回响应代码(而不是我在RestException中设置的响应文本)。
当我的RESTful资源不是EJB时,这个方法运行得非常完美… 有什么想法吗?我已经花了几个小时在这个问题上,现在没有更多的想法了。
谢谢!