Common Helpers

Custom Error Handler

This is used to detect and handle message errors for client and server errors. Play will in many circumstances automatically handle server errors - if your action code throws an exception, Play will catch this and generate a server error page to send to the client. In the snippet below you can see how it is setup for this application.

package controllers

import javax.inject.Singleton

import play.api.Logger
import play.api.http.HttpErrorHandler
import play.api.mvc.RequestHeader
import play.api.mvc.Results._

import scala.concurrent.Future

@Singleton
class CustomErrorHandler extends HttpErrorHandler {

  val log = Logger(this.getClass)

  def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    Future.successful(
      Status(statusCode)("A client error occurred: " + message)
    )
  }

  def onServerError(request: RequestHeader, exception: Throwable) = {
    Future.successful {
      log.error(s"Error occurred ${exception.getMessage}", exception)
      InternalServerError(views.html.error500())
    }
  }
}

The error handler is activate adding the following configuration to your application.conf.


play.http.errorHandler = "CustomErrorHandler"

Finally, in the package views we added the page error500.scala.html that display the errors to the client.

<html>
<body>
<h1>internal error</h1>
<br />
<a href="/">Home</a>
</body>
</html>

Unauthorized Http Action Adapter

This class is used to manage authorization errors. It displays a 401 or a 403 page basing on the error code.

package controllers

import org.pac4j.core.context.HttpConstants
import org.pac4j.play.PlayWebContext
import org.pac4j.play.http.DefaultHttpActionAdapter
import play.mvc.{Result, Results}

class UnauthorizedHttpActionAdapter extends DefaultHttpActionAdapter {

  override def adapt(code: Int, context: PlayWebContext): Result = {
    if (code == HttpConstants.UNAUTHORIZED) {
      Results.unauthorized(views.html.error401.render().toString()).as(HttpConstants.HTML_CONTENT_TYPE)
    } else if (code == HttpConstants.FORBIDDEN) {
      Results.forbidden(views.html.error403.render().toString()).as(HttpConstants.HTML_CONTENT_TYPE)
    } else {
      super.adapt(code, context)
    }
  }
}