How can I redirect to an error page in my Play app?

231 views Asked by At

Or more precisely...

I already have an error page route defined like so:

GET  /error  controllers.pages.ErrorController.page(msg: String, returnTo: String)

And a controller method like this:

object ErrorController extends Controller {
  def page(msg: String, returnTo: String) = ReceiverRestricted { implicit req =>
    val action = List(Button(F8, "Continue", Call("GET", returnTo)))
    Results.Ok(views.html.base(Html("Oops"), List(Html(msg)), None, action))
  }
}

If I programmatically call, say, ErrorController.page("You did something daft!", "/home") I get to a page that looks like I want, ie:

Oops
You did something daft!
F8 Continue

However the url is ugly:

http://localhost:9000/error?msg=You%20did%20something%20daft!&returnTo=/home

I want to change this so the msg= query parameter doesn't appear in the url. How can I accomplish this? I tried removing the query parameter and redirecting to the error page with the message passed in via the flash cookie - that worked but reloading the browser page loses the message. I can't use the session cookie because I already store other data in the session almost upto its limit.

2

There are 2 answers

2
Soroosh Sarabadani On

You can use flash feature. Here is a sample: In your controller you can redirect the user to error page with:

  Redirect("/error").flashing(
    "reason" -> "The item has been created"
  )

And in Error action:

def error = Action { implicit request =>
  Ok {
      val reason =     flash.get("reason").getOrElse("General Error")
      //DO your stuff with reason variable
  }
}

Obviously you can have as many as flash variables you want.

0
Kris On

Since Play is restful and stateless, I can't see an easy way to pass on an error message during a redirect without using Play's flash. Of course you could store the message in an temporary cookie in the browser. Another possibility could be to store it in your database (or whatever persistence technology you use), but this seems to be like cracking a nut with a sledgehammer.