JAX-RS和EJB异常处理

bob*_*nes 7 java ejb exception-handling jax-rs

我在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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是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();
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,对我来说,向最终用户提供响应代码和一些响应文本非常重要.但是,当抛出RestException时,这会导致EJBException(带有消息"EJB抛出一个意外的(未声明的)异常......")也被抛出,并且servlet只将响应代码返回给客户端(和不是我在RestException中设置的响应文本.

当我的RESTful资源不是EJB时,这可以完美地运行......任何想法?我已经在这个工作了好几个小时,而且我都是出于想法.

谢谢!

Del*_*ris 7

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

  • 将RestException更改为已检查的异常并按此处理
  • 在RestException上使用@ApplicationException批注
  • 创建EJBExceptionMapper并从中提取所需的信息 (RestfulException) e.getCause()


lil*_*ili 0

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