play.api.http.DefaultHttpErrorHandler Scala Examples

The following examples show how to use play.api.http.DefaultHttpErrorHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Components.scala    From gbf-raidfinder   with MIT License 6 votes vote down vote up
package walfie.gbf.raidfinder.server

import akka.actor.ActorSystem
import akka.stream.Materializer
import com.trueaccord.scalapb.json.JsonFormat
import monix.execution.Scheduler
import play.api.BuiltInComponents
import play.api.http.{ContentTypes, DefaultHttpErrorHandler}
import play.api.libs.json.Json
import play.api.Mode.Mode
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.core.server._
import play.filters.cors.{CORSConfig, CORSFilter}
import play.filters.gzip.GzipFilterComponents
import scala.concurrent.duration.FiniteDuration
import scala.concurrent.Future
import walfie.gbf.raidfinder.protocol.{RaidBossesResponse, BinaryProtobuf}
import walfie.gbf.raidfinder.RaidFinder
import walfie.gbf.raidfinder.server.controller._
import walfie.gbf.raidfinder.server.syntax.ProtocolConverters.RaidBossDomainOps

class Components(
  raidFinder:                 RaidFinder[BinaryProtobuf],
  translator:                 BossNameTranslator,
  port:                       Int,
  mode:                       Mode,
  websocketKeepAliveInterval: FiniteDuration,
  metricsCollector:           MetricsCollector
) extends NettyServerComponents
  with BuiltInComponents with GzipFilterComponents with Controller {

  override lazy val serverConfig = ServerConfig(port = Some(port), mode = mode)

  private val corsFilter = new CORSFilter(corsConfig = CORSConfig().withAnyOriginAllowed)
  override lazy val httpFilters = List(gzipFilter, corsFilter)

  lazy val websocketController = new WebsocketController(
    raidFinder, translator, websocketKeepAliveInterval, metricsCollector
  )(actorSystem, materializer, Scheduler.Implicits.global)

  // The charset isn't necessary, but without it, Chrome displays Japanese incorrectly
  // if you try to view the JSON directly.
  // https://bugs.chromium.org/p/chromium/issues/detail?id=438464
  private val ContentTypeJsonWithUtf8 = "application/json; charset=utf-8"

  lazy val router = Router.from {
    case GET(p"/") =>
      controllers.Assets.at(path = "/public", "index.html")

    case GET(p"/api/bosses.json" ? q_s"name=$names") =>
      val bosses = if (names.nonEmpty) {
        val knownBossesMap = raidFinder.getKnownBosses
        names.collect(knownBossesMap)
      } else raidFinder.getKnownBosses.values

      val responseProtobuf = RaidBossesResponse(
        raidBosses = bosses.map(_.toProtocol(translator)).toSeq
      )
      val responseJson = JsonFormat.toJsonString(responseProtobuf)
      Action(Ok(responseJson).as(ContentTypeJsonWithUtf8))

    case GET(p"/api/metrics.json") =>
      val activeUsers = metricsCollector.getActiveWebSocketCount()
      val json = Json.obj("activeUsers" -> activeUsers)
      Action(Ok(json))

    case GET(p"/ws/raids" ? q_o"keepAlive=${ bool(keepAlive) }") =>
      websocketController.raids(keepAlive = keepAlive.getOrElse(false))

    case GET(p"/$file*") =>
      controllers.Assets.at(path = "/public", file = file)
  }

  override lazy val httpErrorHandler = new ErrorHandler

  override def serverStopHook = () => Future.successful {
    actorSystem.terminate()
  }
} 
Example 2
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing


class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 3
Source File: ErrorHandler.scala    From izanami   with Apache License 2.0 5 votes vote down vote up
package handlers

import libs.logs.IzanamiLogger
import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import play.core.SourceMapper

import scala.concurrent._

class ErrorHandler(
    env: Environment,
    config: Configuration,
    sourceMapper: Option[SourceMapper],
    router: => Option[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    IzanamiLogger.error(s"Error serving request ${request.method} ${request.uri}", exception)
    Future.successful(
      InternalServerError
    )
  }

} 
Example 4
Source File: ErrorHandler.scala    From scalafiddle-editor   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router

import scala.concurrent._

@Singleton
class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onProdServerError(request: RequestHeader, exception: UsefulException) =
    Future.successful(InternalServerError("A server error occurred: " + exception.getMessage))

  override def onForbidden(request: RequestHeader, message: String) =
    Future.successful(Forbidden("You're not allowed to access this resource."))

  override protected def onNotFound(request: RequestHeader, message: String) =
    Future.successful(NotFound("Resource not found"))

  override protected def onBadRequest(request: RequestHeader, message: String) =
    Future.successful(BadRequest("Bad request"))

} 
Example 5
Source File: ErrorHandler.scala    From recogito2   with Apache License 2.0 5 votes vote down vote up
import javax.inject.{ Inject, Provider }
import play.api.{ Configuration, Environment, Logger, OptionalSourceMapper, UsefulException }
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.RequestHeader
import play.api.mvc.Results._
import play.api.routing.Router
import scala.concurrent.Future

class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
  ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onProdServerError(request: RequestHeader, exception: UsefulException) =
    Future.successful(InternalServerError(s"An error occurred: ${exception.getMessage}"))

  override def onClientError(request: RequestHeader, statusCode: Int, message: String) = {
    if (statusCode == 413) // Request entity too large
      Future.successful(EntityTooLarge("Could not upload the file - too large"))
    else if (statusCode == 404) // Not Found
      Future.successful(NotFound(views.html.error404()))
    else
      super.onClientError(request, statusCode, message)
  }

} 
Example 6
Source File: ErrorHandler.scala    From DataQuality   with GNU Lesser General Public License v3.0 5 votes vote down vote up
package org.openapitools

import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.JsResultException
import play.api.mvc.Results._
import play.api.mvc.{RequestHeader, Result}

import scala.concurrent.Future

class ErrorHandler extends DefaultHttpErrorHandler {
  override def onServerError(request: RequestHeader, e: Throwable): Future[Result] = e match {
    case _: OpenApiExceptions.MissingRequiredParameterException =>
      Future.successful(BadRequest(e.getMessage))
    case _: JsResultException =>
      Future.successful(BadRequest(e.getMessage))
    case _ =>
      // Handles dev mode properly, or otherwise returns internal server error in production mode
      super.onServerError(request, e)
  }
} 
Example 7
Source File: ErrorHandler.scala    From akka-http-test   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc.{ RequestHeader, Result }
import play.api.routing.Router

import scala.concurrent.Future

@Singleton
class ErrorHandler @Inject() (env: Environment, config: Configuration, sourceMapper: OptionalSourceMapper, router: Provider[Router]) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {
  override protected def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    Future.successful(NotFound(Json.obj("path" -> request.path, "messages" -> List("not found", message))))
  }

  override protected def onDevServerError(request: RequestHeader, exception: UsefulException): Future[Result] = {
    Future.successful(InternalServerError(Json.obj("path" -> request.path, "messages" -> List(exception.description))))
  }

  override protected def onProdServerError(request: RequestHeader, exception: UsefulException): Future[Result] = {
    Future.successful(InternalServerError(Json.obj("path" -> request.path, "messages" -> List(exception.description))))
  }

  override protected def onForbidden(request: RequestHeader, message: String): Future[Result] = {
    Future.successful(Forbidden(Json.obj("path" -> request.path, "messages" -> List("forbidden", message))))
  }
} 
Example 8
Source File: ErrorHandler.scala    From Aton   with GNU General Public License v3.0 5 votes vote down vote up
import com.google.inject.Inject
import play.api.{Application, Play}
import play.api.http.{DefaultHttpErrorHandler, HttpErrorHandler, Status}
import play.api.mvc.{RequestHeader, Result, Results}
import views.html.index

import scala.concurrent.Future


class ErrorHandler @Inject()(errorHandler: DefaultHttpErrorHandler) extends HttpErrorHandler {
  override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = {
    statusCode match {
      case clientError if statusCode > 400 && statusCode < 500 => Future.successful(Results.NotFound(index("Aton")))
      case _ => Future.successful(Results.ServiceUnavailable("Unexpected error happened"))
    }
  }

  override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = {
    errorHandler.onServerError(request,exception)
  }
} 
Example 9
Source File: ErrorHandler.scala    From vat-api   with Apache License 2.0 5 votes vote down vote up
package uk.gov.hmrc.vatapi.utils

import javax.inject._
import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import uk.gov.hmrc.http._
import uk.gov.hmrc.vatapi.models.{ErrorBadRequest, ErrorCode, ErrorNotImplemented}

import scala.concurrent._

@Singleton
class ErrorHandler @Inject()(
                              env: Environment,
                              config: Configuration,
                              sourceMapper: OptionalSourceMapper,
                              router: Provider[Router]
                            )(implicit ec: ExecutionContext) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onServerError(request: RequestHeader, ex: Throwable): Future[Result] = {
    super.onServerError(request, ex).map { result =>
      ex match {
        case _ =>
          ex.getCause match {
            case _: NotImplementedException =>
              NotImplemented(Json.toJson(ErrorNotImplemented))
            case _ =>
              Logger.info(s"[ErrorHandler][onServerError] uncaught 5xx Exception")
              result
          }
      }
    }
  }

  override protected def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    super.onBadRequest(request, error).map { _ =>
      error match {
        case "ERROR_VRN_INVALID" => BadRequest(Json.toJson(ErrorBadRequest(ErrorCode.VRN_INVALID, "The provided Vrn is invalid")))
        case "ERROR_INVALID_DATE" => BadRequest(Json.toJson(ErrorBadRequest(ErrorCode.INVALID_DATE, "The provided date is invalid")))
        case "ERROR_INVALID_FROM_DATE" => BadRequest(Json.toJson(ErrorBadRequest(ErrorCode.INVALID_FROM_DATE, "The provided from date is invalid")))
        case "ERROR_INVALID_TO_DATE" => BadRequest(Json.toJson(ErrorBadRequest(ErrorCode.INVALID_TO_DATE, "The provided to date is invalid")))
        case "INVALID_STATUS" | "INVALID_DATE_RANGE" => BadRequest(Json.toJson(Json.obj("statusCode" -> 400, "message" -> error)))
        case unmatchedError => {
          Logger.warn(s"[ErrorHandler][onBadRequest] - Received unmatched error: '$unmatchedError'")
          BadRequest(Json.toJson(Json.obj("statusCode" -> 400, "message" -> JsonErrorSanitiser.sanitise(unmatchedError))))
        }
      }
    }
  }

  override protected def onDevServerError(request: RequestHeader, ex: UsefulException): Future[Result] = {
    super.onServerError(request, ex).map { result =>
      ex match {
        case _ =>
          ex.getCause match {
            case _: NotImplementedException =>
              NotImplemented(Json.toJson(ErrorNotImplemented))
            case _ => result
          }
      }
    }
  }
} 
Example 10
Source File: ErrorHandler.scala    From play-table-of-contents   with MIT License 5 votes vote down vote up
import javax.inject.{Inject, Provider, Singleton}

import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router

import scala.concurrent._


@Singleton
class ErrorHandler @Inject() (
   env: Environment,
   config: Configuration,
   sourceMapper: OptionalSourceMapper,
   router: Provider[Router]
  ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    Future.successful(
      InternalServerError("A server error occurred: " + exception.getMessage)
    )
  }

  override def onForbidden(request: RequestHeader, message: String) = {
    Future.successful(
      Forbidden("You're not allowed to access this resource.")
    )
  }
} 
Example 11
Source File: FeyUIService.scala    From incubator-retired-iota   with Apache License 2.0 5 votes vote down vote up
package org.apache.iota.fey

import org.apache.iota.fey.FeyCore.JSON_TREE
import play.api.BuiltInComponents
import play.api.http.DefaultHttpErrorHandler
import play.api.libs.json.Json
import play.api.mvc._
import play.api.routing.Router
import play.api.routing.sird._
import play.core.server._
import CONFIG._

import scala.concurrent.Future

object FeyUIService {


  val components = new FeyUIService(URL_PATH, PORT)
  val server = components.server
}

class FeyUIService(urlPath: String, port: Int) extends NettyServerComponents with BuiltInComponents {

  val THREAD_SLEEP_TIME = 2000
  lazy val router = Router.from {
    case GET(p"/fey/activeactors") => Action {
      FEY_CORE_ACTOR.actorRef ! JSON_TREE
      Thread.sleep(THREAD_SLEEP_TIME)
      val json = IdentifyFeyActors.generateTreeJson()
      val jsonTree: String = IdentifyFeyActors.getHTMLTree(json)
      Results.Ok(jsonTree).as("text/html")
    }
    case GET(p"/fey/actorslifecycle") => Action {
      val jsonTree = Json.stringify(Monitor.events.printWithEvents)
      Results.Ok(jsonTree).as("application/json")
    }
    case GET(p"/fey/monitoringevents") => Action {
      val returnValue: String = try {
        if (CONFIG.MONITORING_TYPE == "COMPLETE") {
          Monitor.getHTMLevents
        } else {
          Monitor.getSimpleHTMLEvents
        }
      } catch {
        case e: Exception => ""
      }
      Results.Ok(returnValue).as("text/html")
    }
  }

  override lazy val serverConfig = ServerConfig(
    port = Some(port),
    address = urlPath
  )
  override lazy val httpErrorHandler = new DefaultHttpErrorHandler(environment,
    configuration, sourceMapper, Some(router)) {

    override protected def onNotFound(request: RequestHeader, message: String) = {
      Future.successful(Results.NotFound("NO_DATA_FOUND"))
    }
  }
} 
Example 12
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing



@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
                               env: Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: Provider[Router]
                             ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }


  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 13
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing



//@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
                               env: Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: Provider[Router]
                             ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }


  override def onDevServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }


  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 14
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing



@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
                               env: Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: Provider[Router]
                             ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }


  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 15
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing


@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 16
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing



@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
                               env: Environment,
                               config: Configuration,
                               sourceMapper: OptionalSourceMapper,
                               router: Provider[Router]
                             ) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }


  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 17
Source File: ErrorHandler.scala    From daf   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing


@SuppressWarnings(Array("org.wartremover.warts.Equals", "org.wartremover.warts.ExplicitImplicitTypes"))
class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 18
Source File: ErrorHandler.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing

/**
 * The purpose of this ErrorHandler is to override default play's error reporting with application/json content type.
 */
class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
} 
Example 19
Source File: ErrorHandler.scala    From daf-semantics   with Apache License 2.0 5 votes vote down vote up
import javax.inject._

import play.api.http.DefaultHttpErrorHandler
import play.api._
import play.api.mvc._
import play.api.mvc.Results._
import play.api.routing.Router

import scala.concurrent.Future

import de.zalando.play.controllers.PlayBodyParsing


class ErrorHandler @Inject() (
    env: Environment,
    config: Configuration,
    sourceMapper: OptionalSourceMapper,
    router: Provider[Router]
) extends DefaultHttpErrorHandler(env, config, sourceMapper, router) {

  private def contentType(request: RequestHeader): String =
    request.acceptedTypes.map(_.toString).filterNot(_ == "text/html").headOption.getOrElse("application/json")

  override def onProdServerError(request: RequestHeader, exception: UsefulException) = {
    implicit val writer = PlayBodyParsing.anyToWritable[Throwable](contentType(request))
    Future.successful(InternalServerError(exception))
  }

  // called when a route is found, but it was not possible to bind the request parameters
  override def onBadRequest(request: RequestHeader, error: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(BadRequest("Bad Request: " + error))
  }

  // 404 - page not found error
  override def onNotFound(request: RequestHeader, message: String): Future[Result] = {
    implicit val writer = PlayBodyParsing.anyToWritable[String](contentType(request))
    Future.successful(NotFound(request.path))
  }
}