Ethan Mick
Ethan Mick

Reputation: 9567

Return a JSON 404 error in Play 2.4.x

I want to return a custom 404 message when a user hits a route that doesn't exist. I've gotten to:

package controllers

import play.mvc.Results
import play.api.mvc.Results._
import play.api.GlobalSettings
import play.api.mvc.Result
import play.mvc.Http.RequestHeader
import play.libs.{F, Json}

import scala.concurrent.Future

/**
 * Created by ethan on 8/25/15.
 */
object Global extends GlobalSettings {

  override def onHandlerNotFound(request: RequestHeader): Result = {
    NotFound(Json.newObject())
  }

}

But the compiler says method onHandlerNotFound overrides nothing. I believe this is because I'm changing the type of the returned content to be a JSON object, not HTML.

This would work:

override def onHandlerNotFound(request: RequestHeader): Result = {
  Future.successful(NotFound(views.html.errors.notFoundPage()))
}

But I don't want an HTML error page, I want a JSON response.

Future.successful(NotFound(Json.newObject()))

Does not work either.

How can I get my API to return a JSON 404? (This also applies to 500 errors, which I'm running into the same issue).

Edit Final code that worked:

import play.api._
import play.api.libs.json._
import play.api.mvc._
import play.api.mvc.Results._
import scala.concurrent.Future

object Global extends GlobalSettings {

  override def onHandlerNotFound(request: RequestHeader) = {
    Future.successful(NotFound(Json.obj("error" -> "Not Found")))
  }
}

Upvotes: 1

Views: 1308

Answers (1)

Ryan
Ryan

Reputation: 7247

You're mixing the Java and Scala APIs. In Scala, only import from play.api.*.

The compiler is correct—your onHandlerNotFound doesn't override anything because play.api.GlobalSettings doesn't define a method by that name that takes a play.mvc.Http.RequestHeader, that's a type from the Java API. You should be using play.api.mvc.RequestHeader.

The same goes for result types and the JSON library. The two are not inherently compatible, you need to ensure that you don't import from the Java API within Scala and vice versa in Play.

Upvotes: 1

Related Questions