resteasy统一的异常处理handler

来源:互联网 发布:linux查看网卡流量 编辑:程序博客网 时间:2024/05/01 03:31

一般的,我们在使用resteasy api的时候,都会碰到一个问题,若使用spring 管理resteasy api,当在api上使用非编程式事务时,事务的异常无法捕获,因为这个resteasy api的调用是通过远程调用的,这里介绍一下resteasy提供的统一异常处理方法,来解决此问题。

resteasy框架为api的异常处理,提供了一个统一的接口,ExceptionMapper<Exception>,我们可以定义一个handler来实现这个接口,就可以捕获resteasy api的异常,如下面的代码:

@Provider  public class RestExceptionHandler implements ExceptionMapper<Exception> {            @Override      public Response toResponse(Exception e) {                  ResultDto ret = ResultBuilder.buildResultStr(ResultBuilder.FAIL_CODE, null, "-1", e.getMessage());          return Response.status(200).entity(ret).build();      }  }


另外我们需要使用此handler,所以我们在web.xml中启用它,

<context-param>        <param-name>resteasy.providers</param-name>        <param-value>com.bjhit.eranges.rest.provider.RestExceptionHandler</param-value>    </context-param> 

通过这样的配置,我们就可以将resteasy api抛出的异常,通过provider机制捕获,然后修改为前端可以理解的格式返回给前端。