To handle 404 and 500 errors in the Scala Play Framework 2 (2.3), you need to create a Global.scala
object in your main app
directory. The object should extend GlobalSettings
, and override the necessary methods.
The following example Play Framework Global object, saved as app/Global.scala
, demonstrates this:
import play.api._ import play.api.mvc._ import play.api.mvc.Results._ object Global extends GlobalSettings { // called when a route is found, but it was not possible to bind the request parameters override def onBadRequest(request: RequestHeader, error: String) = { BadRequest("Bad Request: " + error) } // 500 - internal server error override def onError(request: RequestHeader, throwable: Throwable) = { InternalServerError(views.html.errors.onError(throwable)) } // 404 - page not found error override def onHandlerNotFound(request: RequestHeader): Result = { NotFound(views.html.errors.onHandlerNotFound(request)) } }
The method views.html.errors.onError(throwable)
refers to a Play template file I named onError.scala.html
, and placed in my app/views/errors
folder. A simple file looks like this:
@(throwable: Throwable) @main("onError Happened") { <h1>onError Happened</h1> <p>@throwable.getMessage</p> }
The method views.html.errors.onHandlerNotFound(request)
refers to a Play template file I named onHandlerNotFound.scala.html
, and is also in my app/views/errors
folder. A simple version of that file looks like this:
@(request: RequestHeader) @main("Handler Not Found") { <h1>Handler Not Found</h1> <p>You requested: @request.path</p> }
More information
For more information, see the following Play Framework pages:
If you want to handle 404 "not found" and 500 "internal server error" errors in your Play Framework 2 application, I hope this post has been helpful.