拦截Jax-RS方法调用

问题描述 投票:0回答:1

[我想截获用@HttpMethod注释或该方法的一些子注释的方法的每个方法调用。

[创建注释不方便,因为我放置了Jax-RS可以调用的每种方法,所以我转到了WriterInterceptorReaderInterceptor

但是,这些不是我想要的,因为我希望它拦截方法调用,而不是读写过程。

过滤器不够好,因为我无法捕获该方法引发的异常。

如果我不必使用任意注释对每个方法进行注释,则第一个解决方案(纯java-ee拦截器)将是最佳选择。

我还有哪些其他选择?

java jakarta-ee jax-rs resteasy
1个回答
0
投票

这可能是特定于容器的,但至少在Wildfly 18上,我认为我可以做你想做的。我使用的是Servlet过滤器和纯JAX-RS-没有任何RestEasy特定的(也不是Spring)。我的Application代码可以:

@ApplicationPath("/rest")
public class RestApplicationConfig extends Application {
    // intentionally empty
}

我的过滤器是:

@WebFilter(urlPatterns = "/rest/*")
public class FilterTest implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        catch( Throwable t ) {
            // handle exception
        }
    }
}

请注意,我在doFilter调用周围进行尝试/捕获。在这里您可以捕获任何异常。一个有趣的补充是我还有一个ContainerRequestFilter

@Provider
@Priority(Priorities.AUTHENTICATION)
@PreMatching
public class AuthContainerRequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException  {
    }
}

并且过滤器中的catch在此代码在Wildfly中运行之前不会被调用。这很有意义,因为这是JAX-RS的一部分。

我的“服务”就是:

@Path("/v1/exception")
public class ExceptionService {
    @Produces({ MediaType.TEXT_PLAIN })
    @GET
    public Response getException() {
        throw new InternalError("this is an internal error");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.