【问题标题】:How to catch Execution exception in scala playframework?如何在scala playframework中捕获执行异常?
【发布时间】:2014-02-11 13:06:25
【问题描述】:

我得到执行异常

[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>

【问题讨论】:

  • 您不应该在发布到该 API 之前检查有效的电子邮件地址吗?盲目地捕获所有异常可能会掩盖其他错误。
  • 您好 Limb,代码使用 3rd 方电子邮件发送,我无法找到他们如何验证他们的电子邮件。所以我想在试图找出使用的验证时发现错误。

标签: forms scala playframework


【解决方案1】:

您可以使用 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))
    }
  }
)

【讨论】:

  • 嗨@Yann Simon 我得到的值 withError 不是 (String, String, String) 的成员顺便说一句,我在视图文件中有这个 @( user: Option[User], form : 形式[(字符串, 字符串, 字符串)])
  • 是的,对不起,您必须先提取表单实例: val form = contactForm.bindFromRequest form.fold ( formWithErrors => ..., c => ... try { ... } catch { ... val formWithError = form.withError(...) ... } )
猜你喜欢
  • 1970-01-01
  • 2012-06-09
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-07
相关资源
最近更新 更多