使用 runAsync 时播放框架处理错误
Play Framework handling error when using runAsync
我在尝试处理负责数据插入的休息服务上的服务器错误时遇到问题。
public CompletableFuture<Result> insertSomething() throws IOException {
JsonNode jsNode = request().body().asJson();
format json node to be used
}
return CompletableFuture.runAsync(() -> {
try {
service.insertSomething(something);
} catch (ParseException e) {
internalServerError();
}
})
.thenApply(future -> created("data inserted"))
.exceptionally(ex -> internalServerError());
}
永远不会抛出 internalServerError,它一直显示 "data inserted"。即使我发送了一些抛出 ParseException 的数据。在调试模式下,我看到它传递了 catch 但没有抛出任何东西。
提前致谢
是因为异常被捕获了。如果你想抛出一个错误,你不需要捕获它。
当然没有抛出任何东西 - 你抓住了吗? exceptionally
只会在 runAsync
内部抛出异常 且代码未处理 时执行。
我找到了答案,我只需要像这样在 catch 中实例化一个 Throwable 类型的对象:
public CompletableFuture<Result> insertSomething() throws IOException {
JsonNode jsNode = request().body().asJson();
format json node to be used
}
return CompletableFuture.runAsync(() -> {
try {
service.insertSomething(something);
} catch (ParseException e) {
new Throwable(e.getMessage());
}
})
.thenApply(future -> created("data inserted"))
.exceptionally(ex -> internalServerError());
}
我在尝试处理负责数据插入的休息服务上的服务器错误时遇到问题。
public CompletableFuture<Result> insertSomething() throws IOException {
JsonNode jsNode = request().body().asJson();
format json node to be used
}
return CompletableFuture.runAsync(() -> {
try {
service.insertSomething(something);
} catch (ParseException e) {
internalServerError();
}
})
.thenApply(future -> created("data inserted"))
.exceptionally(ex -> internalServerError());
}
永远不会抛出 internalServerError,它一直显示 "data inserted"。即使我发送了一些抛出 ParseException 的数据。在调试模式下,我看到它传递了 catch 但没有抛出任何东西。
提前致谢
是因为异常被捕获了。如果你想抛出一个错误,你不需要捕获它。
当然没有抛出任何东西 - 你抓住了吗? exceptionally
只会在 runAsync
内部抛出异常 且代码未处理 时执行。
我找到了答案,我只需要像这样在 catch 中实例化一个 Throwable 类型的对象:
public CompletableFuture<Result> insertSomething() throws IOException {
JsonNode jsNode = request().body().asJson();
format json node to be used
}
return CompletableFuture.runAsync(() -> {
try {
service.insertSomething(something);
} catch (ParseException e) {
new Throwable(e.getMessage());
}
})
.thenApply(future -> created("data inserted"))
.exceptionally(ex -> internalServerError());
}