2014-02-25 103 views
1

我想對異常處理機制提出一些建議。我目前有傳統的try catch,但我明白它在風格上不起作用。那麼處理異常的最佳功能方式是什麼?我試圖尋找Scala的手臂,但它只是一個功能包裝周圍的嘗試抓住最後我想!建議?這裏是我的Play控制器,我想要處理拋出的異常並將純String傳回客戶端!Play框架中的異常處理

def testmethod = Action(parse.maxLength(10 * 1024 * 1024, parser = parse.anyContent)) { implicit request => 
    request.body match { 
     case Left(_) => EntityTooLarge 
     case Right(body) => { 
     println(request.headers.toSimpleMap) 
     val js = // Get the value from the request!!! 

     val resultJsonfut = scala.concurrent.Future { longRunningProcess(js) } 

     Async { 
      if(request.headers.toSimpleMap.exists(_ == (ACCEPT_ENCODING, "gzip"))) { 
      resultJsonfut.map(s => { 
       val bytePayload = getBytePayload(s) // How to handle exceptions thrown by getBytePayLoad???? 
       Ok(bytePayload) 
      }) 
      } else { 
      resultJsonfut.map(s => Ok(s)) 
      } 
     } 
     } 
    } 
    } 

回答

2

您可以創建一個你會打電話來處理你的操作中異常的方法,這個方法會是這個樣子:

def withExceptionHandling(f: => Result)(implicit request: Request[AnyContent]): Result = 
    try{ f }catch{ case e: Exception => InternalServerError("Something bad happened")} 

然後你會使用這樣的:

def testmethod = Action(parse.maxLength(10 * 1024 * 1024, parser = parse.anyContent)) { implicit request => 
    withExceptionHandling { 
    request.body match { 
     case Left(_) => EntityTooLarge 
     case Right(body) => { 
     println(request.headers.toSimpleMap) 
     val js = // Get the value from the request!!! 

     val resultJsonfut = scala.concurrent.Future { longRunningProcess(js) } 

     Async { 
      if(request.headers.toSimpleMap.exists(_ == (ACCEPT_ENCODING, "gzip"))) { 
      resultJsonfut.map(s => { 
       val bytePayload = getBytePayload(s) // How to handle exceptions thrown by getBytePayLoad???? 
       Ok(bytePayload) 
      }) 
      } else { 
      resultJsonfut.map(s => Ok(s)) 
      } 
     } 
     } 
    } 
    } 
} 

這會阻止您明確嘗試並捕獲每個操作。

+0

這聽起來像一個想法。但是你如何處理關閉我們通常在finally塊中執行的流? – sparkr

+0

檢查這個問題,似乎它處理您需要在關閉流/釋放資源方面... http://stackoverflow.com/questions/8865754/scala-finally-block-closing-flushing-resource – Peter