JAX-RS和EJB异常处理

9

我在我的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时,这个方法运行得非常完美… 有什么想法吗?我已经花了几个小时在这个问题上,现在没有更多的想法了。
谢谢!

我有一个类似的用例,我的EJB抛出WebApplicationException并且它可以工作。 - lili
2个回答

11

这个问题似乎与EJB异常处理相关。按照规范,任何从托管bean内部抛出的系统异常(也就是没有明确标记为应用程序异常的运行时异常)都会被封装成EJBException,如果需要,再传递给客户端抛出RemoteException 。您似乎遇到了这种情况,为了避免这种情况,您可以选择:

  • 将RestException更改为受检异常,并将其视为受检异常进行处理
  • 在您的RestException上使用@ApplicationException注释
  • 创建EJBExceptionMapper并从 (RestfulException) e.getCause()中提取所需的信息

0

当 RestException 扩展 javax.ws.rs.WebApplicationException 时,类似的情况对我管用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接