【问题标题】:Handling Exceptions in Play Framework在 Play 框架中处理异常
【发布时间】:2014-03-27 17:56:59
【问题描述】:

我想对异常处理机制提出一些建议。我目前终于有了传统的 try catch,但我知道它在风格上不起作用。那么处理异常的最佳功能方式是什么。我尝试查看 Scala 手臂,但我想它最终只是 try catch 的功能包装器!建议?这是我的 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))
          }
        }
      }
    }
  }

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    你可以创建一个方法来处理你的动作中的异常,这个方法看起来像这样:

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

    这将阻止你明确地尝试和捕捉你的每一个动作。

    【讨论】:

    • 这听起来像是个主意。但是您如何处理我们通常在 finally 块中执行的流的关闭?
    • 检查这个问题,它似乎完全可以满足您在关闭流/释放资源方面的需求...stackoverflow.com/questions/8865754/…
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多