【问题标题】:Exception Mapper not getting invoked in JAX-RS jereyExceptionmapper 未在 JAX-RS 球衣中被调用
【发布时间】:2013-03-03 04:39:07
【问题描述】:

我正在尝试配置一个 ExceptionMapper,它将在我的应用程序中捕获所有与 404 相关的异常。这是我第一次尝试使用这个 ExceptionMapper,因此面临很多问题,可能会丢失一些愚蠢的东西:(

以下是我在 ExceptionMapper 类中所做的:

public class ClassNotFoundMapper implements ExceptionMapper<NotFoundException> {

@Override
public Response toResponse(NotFoundException ex) {
    return Response.status(404).entity(ex.getMessage()).type("text/plain").build();
}

}

web.xml 我添加了这个条目:

<init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>
            com.service.rest;
            com.service.exception
        </param-value>
    </init-param>

服务中我这样做了:

@GET
@Path("{param}")
public Response getName(@PathParam("param") String msg, @HeaderParam("name") String headerName) {

    //SOME CODE HERE AND THEN CONDITIONALLY RETURN THE EXCEPTION
    return Response.status(Response.Status.NOT_FOUND).entity("NOT FOUND").build(); 
}

ExceptionMapper 中存在的异常没有被调用。

请让我知道我错过了什么。

【问题讨论】:

    标签: java web-services rest jax-rs


    【解决方案1】:

    您的ClassNotFoundMapper 上缺少@Provider 注释。

    【讨论】:

    • 感谢您的回复。它适用于为服务触发的 URL 不正确时引发的 404 异常。但同样,如果我从我的应用程序代码中抛出异常(如上面的帖子所示):return Response.status(Response.Status.NOT_FOUND).entity("NOT FOUND").build(); 然后ExceptionMapper 它不会被调用。这有什么具体原因吗?请让我知道。
    • 尝试抛出 NotFoundException 而不是构造 ResponseExceptionMappers 用于未捕获的 Java 异常,而不是用于非 200 状态的Responses。
    猜你喜欢
    • 2019-04-03
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 2011-03-16
    • 2023-03-11
    • 2012-11-29
    • 2014-01-24
    • 2017-08-30
    相关资源
    最近更新 更多