我以web api服务为例,并试图将其调整为基于Mongo的后端。除了我将Transaction.class添加到User.class以及Service实现和web处理程序之外,代码看起来几乎完全相同。
我正在尝试从URL/users/username获取用户json。Mongo正确地检索了它。
我的问题是:我有两段代码,一段工作(返回用户json(,另一段不工作,抛出NPE。
不起作用的代码(它编译了,我不明白为什么不起作用(:
@Override
public void getUser(
String username,
OperationRequest context, Handler<AsyncResult<OperationResponse>> resultHandler) {
resultHandler.handle(
persistence.getUser(username)
.compose(user -> {
if (user.isPresent()) {
System.err.println("D: " + user.get());
return Future.succeededFuture(OperationResponse.completedWithJson(user.get()));
} else {
return Future.succeededFuture(new OperationResponse().setStatusCode(404).setStatusMessage("Not Found"));
}
})
);
}
它有以下例外:
SEVERE: Failed to handleMessage. address: __vertx.reply.1
java.lang.NullPointerException
at io.vertx.ext.web.api.OperationResponseConverter.fromJson(OperationResponseConverter.java:15)
at io.vertx.ext.web.api.OperationResponse.<init>(OperationResponse.java:30)
at io.vertx.ext.web.api.contract.impl.RouteToEBServiceHandler.lambda$handle$1(RouteToEBServiceHandler.java:35)
at io.vertx.core.eventbus.impl.EventBusImpl.lambda$convertHandler$2(EventBusImpl.java:342)
at io.vertx.core.eventbus.impl.HandlerRegistration.deliver(HandlerRegistration.java:278)
...
...
D: {"_id":"5fbebeb97d3c4c0e48f9c7e0","email":"some@user.dk","firstName":"firstname","id":0,"lastName":"lastname","password":"password","phone":"+4512345678","username":"username"}
首先抛出NPE,然后执行System.err.println("D: " + user.get());
并打印用户。浏览器会一直等待回复。
当这段代码运行良好时:
@Override
public void getUser(
String username,
OperationRequest context, Handler<AsyncResult<OperationResponse>> resultHandler) {
persistence.getUser(username).compose(user -> {
if (user.isPresent()) {
resultHandler.handle(Future.succeededFuture(OperationResponse.completedWithJson(user.get())));
return Future.succeededFuture();
} else {
resultHandler.handle(Future.succeededFuture(new OperationResponse().setStatusCode(404).setStatusMessage("Not Found")));
return Future.failedFuture("Error");
}
});
}
有人会认为,将Future.successedFuture((返回到resultHandler.handle((是正确的方法吗?但它抛出了NPE!
我使用这个getUser((持久方法:
@Override
public Future<JsonObject> getUser(String username) {
Promise<JsonObject> promise = Promise.promise();
MongoClient mongoClient = MongoClient.createShared(vertx, mongoconfig);
JsonObject query = new JsonObject().put("username", username);
mongoClient.findOne(collectionName, query, null, promise::handle);
return promise.future();
}
这个服务处理程序:
@Override
public void getUser(
String username,
OperationRequest context, Handler<AsyncResult<OperationResponse>> resultHandler) {
persistence.getUser(username)
.onSuccess(jsonObject -> {
resultHandler.handle(Future.succeededFuture(OperationResponse.completedWithJson(jsonObject)));
});
}
伟大的代码伴随着巨大的责任感。。。一个人必须热爱未来(一旦理解(:(