Juraj
Juraj

Reputation: 181

Play Framework - define 404 page for assets

I'm using Play 2.3 (Java) framework and I want to set a 404 page. I know about onHandlerNotFound method of GlobalSettings.

But assets seem to have their own handling - Assets class doesn't call my onHandlerNotFound method, only sends empty 404 status.

Can I somehow intercept errors in Assets and set my own handling?

It seems to me rather limiting that any asset that doesn't exist returns empty 404 page.

Thanks for any advice.

Edit: some code From routes:

GET     /assets/*file               controllers.Assets.at(path="/public", file)

From GlobalSettings:

@Override
public Promise<Result> onHandlerNotFound(RequestHeader arg0) {
   return Promise.<Result>pure(Results.notFound(
      errPage("notfound")));
}

Upvotes: 0

Views: 1427

Answers (2)

AlexV
AlexV

Reputation: 449

Overriding onHandlerNotFound in the Global will not work here since a handler is found.

For the built in assets controller, when it cannot find a file it uses the onClientError of your project's HttpErrorHandler to get the result to display.

You can look at customizing it here:

Java: https://www.playframework.com/documentation/2.5.x/JavaErrorHandling

Scala: https://www.playframework.com/documentation/2.5.x/ScalaErrorHandling

Here's a Scala example:

import play.api.http.HttpErrorHandler
import play.api.mvc._
import play.api.mvc.Results._
import scala.concurrent._
import javax.inject.Singleton;

@Singleton
class ErrorHandler extends HttpErrorHandler {

  def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    Future.successful(
      // Your custom error page can go here.
      Status(statusCode)("A client error occurred: " + message)
    )
  }
}

Upvotes: 1

hamena314
hamena314

Reputation: 3109

I think this is a very similar question to the one asked in a different thread.

If you are using assets, I assume they are some objects like files? If so, you need to take a look at the second part of the solution from here:

How to create a custom 404 page handler with Play 2.0?

The one where Andrew E writes about "Real Handler can't find object" Scenario. That part is about a user requesting an object that simply does not exist.

Upvotes: 0

Related Questions