2014-08-28 94 views
4

我正在使用播放框架開發REST API。我想爲我的所有操作實施集中的錯誤處理。播放框架中的錯誤處理

達到此目的的最佳方法是什麼?

+0

你看過Scala Future和Play之前的行動/結果嗎? – cchantep 2014-08-28 11:46:10

+0

@applicius:我不太清楚你的評論如何解釋正確的地方執行*集中*在播放應用程序中的錯誤處理... – jfu 2014-08-28 11:56:15

+0

我很不確定你有沒有閱讀Play框架文檔關於行動,動作組合,行動構建和使用未來。 – cchantep 2014-08-28 12:01:24

回答

5

你應該看看GlobalSettingshttps://www.playframework.com/documentation/2.3.x/ScalaGlobal

尤其是,它可以讓你覆蓋:

def onError(request: RequestHeader, ex: Throwable) 
def onHandlerNotFound(request: RequestHeader) 
def onBadRequest(request: RequestHeader, error: String) 

onError可能是你正在尋找的一個,但其他人可能是太有用:)

5

的另一種方式做,這是使用filter,如:

object ExceptionFilter extends EssentialFilter { 
    def apply(nextFilter: EssentialAction) = new EssentialAction { 
    def apply(requestHeader: RequestHeader) = { 
     val next: Iteratee[Array[Byte], Result] = nextFilter(requestHeader) 

     // Say your backend throws an ItemNotFound exception. 
     next recoverWith { 
     case e: ItemNotFound => Iteratee.ignore[Array[Byte]] 
      .map(_ => Results.NotFound("Item not in the database!")) 
     } 
    } 
    } 
} 

然後鉤住了在全局設置:

object Global extends WithFilters(CSRFFilter(), ExceptionFilter) with GlobalSettings 

這可能允許在需要時您做一些與請求主體。我同意在大多數情況下使用GlobalSettings.onError可能是最簡單的方法。