resteasy统一的异常处理handler

xiaoxiao2021-02-28  115

一般的,我们在使用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机制捕获,然后修改为前端可以理解的格式返回给前端。

 

最后欢迎大家访问我的个人网站:1024s

转载请注明原文地址: https://www.6miu.com/read-24688.html

最新回复(0)