10

我的控制器操作代码如下所示:

  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(...) 返回一个 Promise[Ingredient] 但也可以抛出一个自定义 ValidationException。当抛出此异常时,我想返回注释代码。

目前页面呈现为 500 并且在我的日志中:

播放 - 等待承诺,但出现错误:名称为“测试”的成分已存在。services.ValidationException:名称为“test”的成分已存在。

两个问题:

  • 从我的服务中返回此异常是一个坏主意,是否有更好/更多的 scala 方法来处理这种情况?
  • 我如何捕捉异常?
4

2 回答 2

2

我想说一种纯粹的功能方式是使用一种可以保持有效和错误状态的类型。

为此,您可以使用验证表单 scalaz

但是,如果不需要更多来自 scalaz 的内容(您将 ^^),您可以使用一个非常简单的东西,使用 aPromise[Either[String, Ingredient]]作为结果及其fold在 Async 块中的方法。也就是说,map在兑现承诺时和兑现的东西上转换价值fold

好点 => 没有例外 => 每件事都是输入检查:-)

编辑

它可能需要更多信息,这里有两个选项:try catch,感谢@kheraud)和 Either。没放Validation,有需要的问我。对象应用扩展控制器{

  def index = Action {
    Ok(views.html.index("Your new application is ready."))
  }

  //Using Try Catch
  //  What was missing was the wrapping of the BadRequest into a Promise since the Async
  //    is requiring such result. That's done using Promise.pure
  def test1 = Async {
    try {
      val created = Promise.pure(new {val name:String = "myname"})
      created map { stuff =>
        Redirect(routes.Application.index()).flashing("success" -> "Stuff '%s' show".format(stuff.name))
      }
    } catch {
      case _ => {
        Promise.pure(Redirect(routes.Application.index()).flashing("error" -> "an error occurred man"))
      }
    }
  }


  //Using Either (kind of Validation)
  //  on the Left side => a success value with a name
  val success = Left(new {val name:String = "myname"})
  //  on the Right side the exception message (could be an Exception instance however => to keep the stack)
  val fail = Right("Bang bang!")

  // How to use that
  //   I simulate your service using Promise.pure that wraps the Either result
  //    so the return type of service should be Promise[Either[{val name:String}, String]] in this exemple
  //   Then while mapping (that is create a Promise around the convert content), we folds to create the right Result (Redirect in this case).
  // the good point => completely compiled time checked ! and no wrapping with pure for the error case.
  def test2(trySuccess:Boolean) = Async {
      val created = Promise.pure(if (trySuccess) success else fail)
      created map { stuff /* the either */ =>
        stuff.fold(
          /*success case*/s => Redirect(routes.Application.index()).flashing("success" -> "Stuff '%s' show".format(s.name)),
          /*the error case*/f => Redirect(routes.Application.index()).flashing("error" -> f)
        )

      }

  }

}
于 2012-06-06T12:31:19.907 回答
0

您不能在 Async 块中捕获异常吗?

Async {
    try {
        val created = Service.addIngredient(value.name, value.description)
        created map { ingredient =>
            Redirect(routes.Admin.index()).flashing("success" -> "Ingredient '%s' added".format(ingredient.name))
        }
     } catch {
         case _ => {
             Promise.pure(Redirect(routes.Admin.index()).flashing("error" -> "Error while addin ingrdient"))
         }
     }
}
于 2012-06-06T11:48:11.120 回答