如何捕获scala playframework中的执行异常?

时间:2014-02-11 13:06:26

标签: forms scala playframework

我收到执行例外

  

[APIError:您必须提供一个电子邮件地址才能创建一张票。]

可以捕获此错误并仅发布

  

“您必须提供电子邮件地址才能创建票证。”

此错误应显示在视图页面中。

给出错误的代码:

val question = uservoice.post("/api/v1/tickets.json", ticket).getJSONObject("ticket")

控制器:

def contactSave = withOptionUser { user => implicit request =>
    contactForm.bindFromRequest.fold(
      formWithErrors => BadRequest(html.anon.contact(user, formWithErrors)),
      c => {
          val uservoice = new com.uservoice.Client(SUBDOMAIN, API_KEY, API_SECRET)

          val ticketMsg = Map("state" -> "open","subject" -> c._2, "message" -> c._3).toMap[String,Object].asJava

          val ticket = Map("email" -> c._1, "ticket" -> ticketMsg).toMap[String,Object].asJava

          Logger.debug(ticket.toString)

          val question = uservoice.post("/api/v1/tickets.json", ticket).getJSONObject("ticket")

          Logger.debug(question.toString)

          Ok(views.html.anon.contactThanks(user))
      }
    )
  }

Html:

@main("Contact Us",user,"contact",stylesheet, scripts) {
    @helper.form(routes.UservoiceController.contactSave) {
<section class="contact">
    <div class="contactBox contentBox">
        <div class="leftColumn">
            <h1>Contact Us</h1>
            <span>You can fill out this form for any general inquiries, comments, etc.</span>
            <span>You can also find us on Facebook and Twitter!</span>

            <div class="social">
                @form.globalError.map { error =>
                <span class="error" data-xpl="loginError">
                    @error.message
                </span>

1 个答案:

答案 0 :(得分:0)

您可以使用try / catch块并创建表单

var form = contactForm.bindFromRequest()
form.fold(
  formWithErrors => ...
  c => {
    ...
    try {
      val question = uservoice.post("/api/v1/tickets.json", ticket).getJSONObject("ticket")
      Logger.debug(question.toString)
      Ok(views.html.anon.contactThanks(user))
    } catch {
      case e: Exception =>
        Logger.error("error ...", e)
        val formWithError = form.withError("email", "You must provide an email address in order to create a ticket.")
        BadRequest(html.anon.contact(user, formWithError))
    }
  }
)