簡體   English   中英

在Play框架中處理異常

[英]Handling Exceptions in Play Framework

我想對異常處理機制提出一些建議。 目前,我終於有了傳統的試吃產品,但我知道它在功能上不起作用。 那么處理異常的最佳功能方法是什么。 我試着研究了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))
          }
        }
      }
    }
  }

您可以創建一個調用該方法以處理Action內部異常的方法,該方法如下所示:

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

這將阻止您顯式嘗試並抓住每個動作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM