我有一个 RESTful 资源,它调用 EJB 来进行查询。如果查询没有结果,EJB 将抛出 EntityNotFoundException。在 catch 块中,将抛出 javax.xml.ws.http.HTTPException ,代码为 404。
@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 代码?
Thanks,
拉斐尔·阿方索
javax.xml.ws.http.HTTPException https://docs.oracle.com/javase/7/docs/api/javax/xml/ws/http/HTTPException.html适用于 JAX-WS。默认情况下,JAX-RS 不知道如何处理它,除非你写一个ExceptionMapper
为了它。因此,异常会向上冒泡到容器级别,容器仅发送通用的内部服务器错误响应。
而是使用WebApplicationException http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html或其子类之一。这里列出了层次结构中包含的异常以及它们映射到的内容(注意:这仅在 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
, or ServerErrorException
.
对于 JAX-RS 1.x,此层次结构不存在,因此您需要执行 @RafaelAlfonso 在评论中显示的操作
throw new WebApplicationException(Response.Status.NOT_FOUND);
还有很多其他可能的构造函数。只需查看上面的 API 链接即可
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)