我有一个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);
}
}
}当我使用没有结果的代码调用Rest服务时,将打印EntityNotFoundException catch块中的日志消息。但是,我的客户端接收HTTP代码500而不是404。为什么我没有收到404代码?
谢谢,
拉斐尔·阿丰索
发布于 2015-04-23 20:37:37
javax.xml.ws.http.HTTPException是给JAX的.默认情况下,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您也可以在上面的WebApplicationException链接中找到它们。它们将属于直接子类ClientErrorException、RedirectionException或ServerErrorException。
对于JAX-RS1.x,这个层次结构不存在,所以您需要执行@RafaelAlfonso这样的注释。
throw new WebApplicationException(Response.Status.NOT_FOUND);还有很多其他的可能的构造者。只需查看上面的API链接
https://stackoverflow.com/questions/29833553
复制相似问题