2014-02-11 63 views
0

我得到執行異常如何捕捉scala playframework中的執行異常?

[APIError: You must provide an email address in order to create a ticket.]

有可能趕上這個錯誤,並張貼只有

"You must provide an email address in order to create a ticket."

這個錯誤應該在視圖頁面showup。

,讓錯誤代碼:

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> 
+0

在發佈到該API之前,您不應該檢查有效的電子郵件地址嗎?盲目捕捉所有異常情況可能會掩蓋其他錯誤。 –

+0

嗨肢體,代碼是使用第三方電子郵件發送,我無法找到他們如何驗證他們的電子郵件..所以我想在找出使用的驗證時趕上錯誤。 – Monnster

回答

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)) 
    } 
    } 
) 
+0

您好@Yann西蒙我得到價值withError不是(String,String,String)的成員 順便說一下,我在查看文件 @(user:Option [User], form:Form [ (字符串,字符串,字符串)] ) – Monnster

+0

是的,對不起,你必須先提取表單實例: VAL形式= contactForm.bindFromRequest form.fold( formWithErrors => ..., C => ... 嘗試{ ... } catch { ... val formWithError = form.withError(...) ... } ) –