我编写了一个代码,如果未在数据库中找到URL中指定的列表ID,则将引发以下消息。它应该发送带有错误消息的json响应,但是我也收到带有消息的异常类名称:
其余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());