首页 文章

JAX-RS和EJB异常处理

提问于
浏览
6

我在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时,这可以完美地运行......任何想法?我已经在这个工作了好几个小时,而且我都是出于想法 .

谢谢!

2 回答

  • 6

    该问题似乎与EJB异常处理有关 . 根据规范,从托管bean中抛出的任何 system exception (即 - 任何未明确标记为Application Exception的RuntimeException)将被打包到EJBException中,并在以后(如果需要)打包到抛出到客户端的RemoteException中 . 这是你似乎处于的一种情况,为了避免这种情况,你可以:

    • 将RestException更改为已检查的异常并按此处理

    • 在您的RestException上使用@ApplicationException注释

    • 创建EJBExceptionMapper并从 (RestfulException) e.getCause() 中提取所需的信息

  • 0

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

相关问题