gpt4 book ai didi

java - Rest API json 响应中出现异常完整类名

转载 作者:行者123 更新时间:2023-12-01 19:33:54 26 4
gpt4 key购买 nike

我编写了一个代码,如果在数据库中找不到 URL 中指定的列表 ID,它将抛出以下消息。它应该发送带有错误消息的 json 响应,但我也收到异常类名称和消息:

rest API 的预期输出:

 {
"code": 404,
"message": "Watchlist dnd was not found"
}

代码:

@RolesAllowed({ "admin" })
@Path("/{listId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns a watchlist.", notes = "")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "The watchlist was returned.", response = Watchlist.class),
@ApiResponse(code = 404, message = "The watchlist was not found.", response = ErrorMessage.class),
@ApiResponse(code = 500, message = "Internal server error.", response = ErrorMessage.class) })
public Watchlist getList(@PathParam("listId") String listId, @HeaderParam("x-access-token") String jwtToken,
@Context SecurityContext sec, @Context final HttpServletResponse response) throws Exception {

final String sourceMethod = "getList";
if (logger.isLoggable(Level.FINER)) {
logger.entering(CLASSNAME, sourceMethod);
}
WatchlistService service = new WatchlistService(cedmPersitence);
Watchlist list = service.getWatchList(listId);

if (logger.isLoggable(Level.FINER)) {
logger.exiting(CLASSNAME, sourceMethod);
}

return list;
}




public Watchlist getWatchList(String listId) throws IOException,NotFoundException{

Watchlist list = new Watchlist();
list.setListId(listId);


if(listId !=null) {
HBasePersistence persistence = new HBasePersistence();
persistence.init("watchlist");
List<WatchlistEntry> watchListEntries = persistence.getWatchlistByListId(listId);
if (watchListEntries == null || watchListEntries.isEmpty()) {
throw new NotFoundException("Watchlist " + listId + " was not found");
}
list.setEntries(watchListEntries);

}

return list;
}

但我收到了这样的回复:

{
"code": 404,
"message": "class com.ibm.cedm.exception.NotFoundException:Watchlist dnd was not found"
}

有人知道为什么会这样吗?

最佳答案

正如您在引用文献中看到的: https://docs.oracle.com/javaee/7/api/javax/ws/rs/NotFoundException.html#NotFoundException-java.lang.String- ,当您将错误消息传递给 NotFoundException 时,Throwable.getMessage() 肯定会使用类名来丰富该消息。

NotFoundException 还接受 Response 作为参数,因此您可以通过传递 Response 来构建响应,而不是传递消息。

final Response.ResponseBuilder response = Response.status(Response.Status.NOT_FOUND);

response.entity("Watchlist " + listId + " was not found").type("text/plain");

throw new NotFoundException(response.build());

关于java - Rest API json 响应中出现异常完整类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59238355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com