Il mio codice azione di controllo è simile al seguente:Come gestire le eccezioni in un blocco play framework 2 Async (Scala)
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())))))
}
})
}
mio Service.addIngredient (...) restituisce una promessa [ingrediente], ma può anche buttare una ValidationException personalizzata. Quando viene generata questa eccezione, desidero restituire il codice commentato.
Attualmente pagina rende come 500 e nei registri ho:
play - Waiting for a promise, but got an error: Ingredient with name 'test' already exists. services.ValidationException: Ingredient with name 'test' already exists.
Due domande:
- E 'una cattiva idea di tornare questa eccezione dal mio servizio, c'è una migliore/più scala per gestire questo caso?
- Come rilevare l'eccezione?
C'era un bug che è stato fissato un paio di giorni fa. Vedi [questo commit] (https://github.com/playframework/Play20/commit/def888333ea435437edb7f70ca3b7f48877af1c7). Puoi gestire le eccezioni del runtime nell'hook 'onError' del tuo oggetto' Global'. –
ma non c'è modo di rilevare l'eccezione localmente? – Somatik
Sì, puoi prenderlo come qualsiasi altra eccezione, come mostrato nella risposta del kheraud. –