Jonik Jonik - 1 month ago 5
Scala Question

How to disable HTML error responses when using Action(parse.json)?

In a REST API implemented with Play Framework (2.4), I'm using

to parse JSON from incoming POST request body.

With my current code (see below),


  • Posting valid JSON with missing fields (e.g.
    {"foo": ""}
    ) produces
    400 with the response body
    {"error":"Missing input fields"}
    . This is fine and expected.

Answer

The long html is produced by the default HttpErrorHandler. You can provide your own by following this guide. Quoting the example code:

class ErrorHandler extends HttpErrorHandler {

  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(
      InternalServerError("A server error occurred: " + exception.getMessage)
    )
  }
}

Note: if you manage your dependencies without Guice, you will have to provide your custom HttpErrorHandler in the ApplicationLoader

Comments