2014-02-25 98 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