JAX-RS服务抛出404 HTTPException但客户端接收HTTP 500代码

Raf*_*nso 3 java jax-rs

我有一个RESTful资源,它调用EJB来进行查询.如果查询没有结果,则EJB抛出EntityNotFoundException.在catch块中,将抛出一个代码为404的javax.xml.ws.http.HTTPException.

@Stateless
@Path("naturezas")
public class NaturezasResource {

    @GET
    @Path("list/{code}")
    @Produces(MediaType.APPLICATION_JSON)
    public String listByLista(
            @PathParam("code") codeListaNaturezasEnum code) {
        try {
            List<NaturezaORM> naturezas = this.naturezaSB
                    .listByListaNaturezas(code);
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(naturezas);
        } catch (EntityNotFoundException e) { // No data found
            logger.error("there is no Natures with the code " + code);
            throw new HTTPException(404);
        } catch (Exception e) { // Other exceptions
            e.printStackTrace();
            throw new HTTPException(500);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

当我使用没有结果的代码调用Rest Service时,将EntityNotFoundException打印catch块内的日志消息.但是,我的客户端收到HTTP代码500而不是404.为什么我没有收到404代码?

谢谢,

Rafael Afonso

Pau*_*tha 8

javax.xml.ws.http.HTTPException适用于JAX-WS.JAX-RS默认情况下不知道如何处理它,除非你ExceptionMapper为它写一个.因此异常冒泡到容器级别,它只发送一个通用的内部服务器错误响应.

而是使用WebApplicationException或其子类之一.这里是层次结构中包含的异常列表,以及它们映射到的内容(注意:这仅在JAX-RS 2中)

Exception                      Status code    Description
-------------------------------------------------------------------------------
BadRequestException            400            Malformed message
NotAuthorizedException         401            Authentication failure
ForbiddenException             403            Not permitted to access
NotFoundException              404            Couldn’t find resource
NotAllowedException            405            HTTP method not supported
NotAcceptableException         406            Client media type requested 
                                                            not supported
NotSupportedException          415            Client posted media type 
                                                            not supported
InternalServerErrorException   500            General server error
ServiceUnavailableException    503            Server is temporarily unavailable 
                                                            or busy
Run Code Online (Sandbox Code Playgroud)

您也可以在WebApplicationException上面的链接中找到它们.他们将下降的直接的一个子类下ClientErrorException,RedirectionExceptionServerErrorException.

使用JAX-RS 1.x时,此层次结构不存在,因此您需要执行@RafaelAlfonso在评论中显示的内容

throw new WebApplicationException(Response.Status.NOT_FOUND);
Run Code Online (Sandbox Code Playgroud)

还有很多其他可能的构造函数.只需查看上面的API链接即可