Global exception handling with Play 2.0

facebooktwittergoogle_pluslinkedin

Today just a small gem that still took my way too long to figure out. Mainly because the documentation of the Play Framework isn’t at its best.

I wanted to add some sort of global error handling to my play application. So the goal is, that I can specify the behavior based on the type of the exception that is thrown during run time in one place. As I know Spring MVC fairly well, I was first looking for something like a exception resolver, where I could register custom resolvers which then specify what should happen in case of a certain exception. I did not find anything like that.

Finally, when looking through the application.conf file, I found the an object trait GlobalSettings and with that I found the according documentation: ScalaGlobal

With that, it should be fairly simple to write your own global error handling, especially with pattern matching. This is how it looks so far in my application:

import controllers.JsonResponse._

object Global extends GlobalSettings {
  override def onError(request: RequestHeader, ex: Throwable): Result = ex.getCause match {
    case _: NoSuchElementException  => NoSuchElement
    case _ => super.onError(request, ex)
  }
}

So currently it only treats a NoSuchElementException differently. But further exceptions will be added shortly. The value NoSuchElement: Result comes from JsonResponse object and simply creates a Json error code and a NotFound Response Header.

In a first attempt I didn’t use ex.getCause but directly ex for the pattern matching. But then everything is a PlayException.

If there is still a better way to solve this issue, let me know!