2014-02-25 3 views
1

예외 처리 메커니즘에 대한 제안 사항이 있습니다. 나는 현재 전통적인 시도 잡기를 마침내 가지고 있지만 그것이 스타일로 작동하지 않는 것을 이해합니다. 그렇다면 예외를 처리하는 최상의 기능적 방법은 무엇입니까? 스칼라 팔을 살펴 보았지만, 필자가 생각한 try catch를 둘러싼 기능적인 래퍼 일뿐입니다! 제안? 다음은 던져진 예외를 처리하고 일반 문자열을 클라이언트에 다시 보내려는 Play 컨트롤러입니다.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

아이디어와 비슷합니다. 그러나 우리는 마침내 블록에서 정상적으로 수행하는 스트림 닫기를 어떻게 처리합니까? – sparkr

+0

이 질문을 확인하십시오, 스트림을 닫는/리소스를 해제하는 측면에서 정확히 필요한 것을 처리하는 것 같습니다 ... http://stackoverflow.com/questions/8865754/scala-finally-block-closing-flushing-resource – Peter

관련 문제