我的控制器操作的代碼如下所示:如何處理異常的playframework 2異步塊(斯卡拉)
def addIngredient() = Action { implicit request =>
val boundForm = ingredientForm.bindFromRequest
boundForm.fold(
formWithErrors => BadRequest(views.html.Admin.index(formWithErrors)),
value => {
Async {
val created = Service.addIngredient(value.name, value.description)
created map { ingredient =>
Redirect(routes.Admin.index()).flashing("success" -> "Ingredient '%s' added".format(ingredient.name))
}
// TODO on exception do the following
// BadRequest(views.html.Admin.index(boundForm.copy(errors = Seq(FormError("", ex.getMessage())))))
}
})
}
我Service.addIngredient(...)返回一個無極[成分],但也可以拋出一個自定義的ValidationException。當拋出這個異常時,我想返回註釋的代碼。
目前的頁面呈現在500nm和在日誌中我有:
play - Waiting for a promise, but got an error: Ingredient with name 'test' already exists. services.ValidationException: Ingredient with name 'test' already exists.
兩個問題:
- 它是一個壞主意,我的服務回報這個例外,有沒有更好的/更多scala的方式來處理這種情況?
- 如何捕捉異常?
有已在幾天前修正了一個錯誤。看[這個提交](https://github.com/playframework/Play20/commit/def888333ea435437edb7f70ca3b7f48877af1c7)。您可以在'Global'對象的'onError'鉤子中處理運行時異常。 –
但是沒有辦法在本地捕獲異常? – Somatik
是的,你可以像其他異常一樣捕捉它,如kheraud的答案所示。 –