play.api.http.HttpErrorHandler Scala Examples
The following examples show how to use play.api.http.HttpErrorHandler.
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: ErrorHandler.scala From gbf-raidfinder with MIT License | 5 votes |
package walfie.gbf.raidfinder.server import play.api.http.HttpErrorHandler import play.api.libs.json._ import play.api.mvc._ import play.api.mvc.Results._ import scala.concurrent.Future class ErrorHandler extends HttpErrorHandler { // TODO: Make this more structured private def jsonResponse(statusCode: Int, message: String): JsObject = Json.obj( "errors" -> Json.arr( Json.obj( "status" -> statusCode, "detail" -> message ) ) ) def onClientError( request: RequestHeader, statusCode: Int, message: String ): Future[Result] = Future.successful { Status(statusCode)(jsonResponse(statusCode, message)) } def onServerError( request: RequestHeader, exception: Throwable ): Future[Result] = Future.successful { InternalServerError(jsonResponse(500, "Internal server error")) } }
Example 2
Source File: VersionRoutingRequestHandler.scala From vat-api with Apache License 2.0 | 5 votes |
package routing import config.{AppConfig, FeatureSwitch} import definition.Versions import javax.inject.{Inject, Singleton} import play.api.http.{DefaultHttpRequestHandler, HttpConfiguration, HttpErrorHandler, HttpFilters} import play.api.libs.json.Json import play.api.mvc.{DefaultActionBuilder, Handler, RequestHeader, Results} import play.api.routing.Router import v1.controllers.requestParsers.validators.validations.VrnValidation import v1.models.errors.{InvalidAcceptHeaderError, UnsupportedVersionError, VrnFormatError} @Singleton class VersionRoutingRequestHandler @Inject()(versionRoutingMap: VersionRoutingMap, errorHandler: HttpErrorHandler, httpConfiguration: HttpConfiguration, config: AppConfig, filters: HttpFilters, action: DefaultActionBuilder) extends DefaultHttpRequestHandler(versionRoutingMap.defaultRouter, errorHandler, httpConfiguration, filters) { private val featureSwitch = FeatureSwitch(config.featureSwitch) private val unsupportedVersionAction = action(Results.NotFound(Json.toJson(UnsupportedVersionError))) private val invalidAcceptHeaderError = action(Results.NotAcceptable(Json.toJson(InvalidAcceptHeaderError))) override def routeRequest(request: RequestHeader): Option[Handler] = { def documentHandler = routeWith(versionRoutingMap.defaultRouter)(request) def apiHandler = Versions.getFromRequest(request) match { case Some(version) => versionRoutingMap.versionRouter(version) match { case Some(versionRouter) if featureSwitch.isVersionEnabled(version) => routeWith(versionRouter)(request) case Some(_) => Some(unsupportedVersionAction) case None => Some(unsupportedVersionAction) } case None => Some(invalidAcceptHeaderError) } documentHandler orElse apiHandler } private def routeWith(router: Router)(request: RequestHeader) = router .handlerFor(request) .orElse { if (validatePath(request.path)) { if (request.path.endsWith("/")) { val pathWithoutSlash = request.path.dropRight(1) val requestWithModifiedPath = request.withTarget(request.target.withPath(pathWithoutSlash)) router.handlerFor(requestWithModifiedPath) } else None } else { Some(action(Results.BadRequest(Json.toJson(VrnFormatError)))) } } private def validatePath(path: String) = { val vrn = path.split("/")(1) if(VrnValidation.validate(vrn) == Nil) true else false } }
Example 3
Source File: DocumentationController.scala From vat-api with Apache License 2.0 | 5 votes |
package config import controllers.Assets import definition.ApiDefinitionFactory import javax.inject.{Inject, Singleton} import play.api.http.HttpErrorHandler import play.api.libs.json.Json import play.api.mvc.{Action, AnyContent, ControllerComponents} import uk.gov.hmrc.api.controllers.{DocumentationController => HmrcDocumentationController} @Singleton class DocumentationController @Inject()(vatApiDefinition: ApiDefinitionFactory, cc: ControllerComponents, assets: Assets, errorHandler: HttpErrorHandler) extends HmrcDocumentationController(cc,assets , errorHandler ) { override def definition(): Action[AnyContent] = Action { Ok(Json.toJson(vatApiDefinition.definition)) } def raml(version: String, file: String): Action[AnyContent] = { assets.at(s"/public/api/conf/$version", file) } }
Example 4
Source File: DocumentationController.scala From vat-api with Apache License 2.0 | 5 votes |
package uk.gov.hmrc.vatapi.controllers.definition import controllers.Assets import javax.inject.{Inject, Singleton} import play.api.http.HttpErrorHandler import play.api.libs.json.Json import play.api.mvc.{Action, AnyContent, ControllerComponents} import uk.gov.hmrc.api.controllers.{DocumentationController => HmrcDocumentationController} import uk.gov.hmrc.vatapi.controllers.definition.JsonFormatters._ @Singleton class DocumentationController @Inject()(vatApiDefinition: VatApiDefinition, cc: ControllerComponents, assets: Assets, errorHandler: HttpErrorHandler) extends HmrcDocumentationController(cc, assets , errorHandler ) { override def definition() = Action { Ok(Json.toJson(vatApiDefinition.definition)) } def raml(version: String, file: String): Action[AnyContent] = { assets.at(s"/public/api/conf/$version", file) } }
Example 5
Source File: ErrorHandler.scala From Aton with GNU General Public License v3.0 | 5 votes |
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 6
Source File: AssetCtrl.scala From Cortex with GNU Affero General Public License v3.0 | 5 votes |
package org.thp.cortex.controllers import javax.inject.{Inject, Singleton} import play.api.http.{FileMimeTypes, HttpErrorHandler} import play.api.mvc.{Action, AnyContent} import controllers.{Assets, AssetsMetadata, ExternalAssets} import play.api.Environment import scala.concurrent.ExecutionContext trait AssetCtrl { def get(file: String): Action[AnyContent] } @Singleton class AssetCtrlProd @Inject()(errorHandler: HttpErrorHandler, meta: AssetsMetadata) extends Assets(errorHandler, meta) with AssetCtrl { def get(file: String): Action[AnyContent] = at("/www", file) } @Singleton class AssetCtrlDev @Inject()(environment: Environment)(implicit ec: ExecutionContext, fileMimeTypes: FileMimeTypes) extends ExternalAssets(environment) with AssetCtrl { def get(file: String): Action[AnyContent] = at("www/dist", file) }
Example 7
Source File: PlayComponents.scala From endpoints4s with MIT License | 5 votes |
package endpoints4s.play.server import play.api.BuiltInComponents import play.api.http.{FileMimeTypes, HttpErrorHandler} import play.api.mvc.{DefaultActionBuilder, PlayBodyParsers} import scala.concurrent.ExecutionContext def fromBuiltInComponents( builtInComponents: BuiltInComponents ): PlayComponents = new PlayComponents { def playBodyParsers: PlayBodyParsers = builtInComponents.playBodyParsers def httpErrorHandler: HttpErrorHandler = builtInComponents.httpErrorHandler def defaultActionBuilder: DefaultActionBuilder = builtInComponents.defaultActionBuilder def fileMimeTypes: FileMimeTypes = builtInComponents.fileMimeTypes implicit def executionContext: ExecutionContext = builtInComponents.executionContext } }
Example 8
Source File: DocumentationController.scala From self-assessment-api with Apache License 2.0 | 5 votes |
package router.controllers import controllers.Assets import javax.inject.{Inject, Singleton} import play.api.http.HttpErrorHandler import play.api.libs.json.Json import play.api.mvc.{Action, AnyContent, ControllerComponents} import router.definition.SelfAssessmentApiDefinition import uk.gov.hmrc.api.controllers.{DocumentationController => HmrcDocumentationController} @Singleton class DocumentationController @Inject()(selfAssessmentApiDefinition: SelfAssessmentApiDefinition, cc: ControllerComponents, assets: Assets, errorHandler: HttpErrorHandler) extends HmrcDocumentationController(cc, assets, errorHandler) { override def definition(): Action[AnyContent] = Action { Ok(Json.toJson(selfAssessmentApiDefinition.definition)) } override def conf(version: String, file: String): Action[AnyContent] = { assets.at(s"/public/api/conf/$version", file) } }
Example 9
Source File: HatBodyParsers.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.utils import javax.inject.Inject import play.api.http.{ HttpErrorHandler, Status } import play.api.libs.json.{ JsError, Reads } import play.api.mvc.{ BodyParser, PlayBodyParsers } import scala.concurrent.{ ExecutionContext, Future } class HatBodyParsers @Inject() (errorHandler: HttpErrorHandler, playBodyParsers: PlayBodyParsers)( implicit val ec: ExecutionContext) { def json[A](implicit reader: Reads[A]): BodyParser[A] = BodyParser("json reader") { request => playBodyParsers.json(request) mapFuture { case Left(simpleResult) => Future.successful(Left(simpleResult)) case Right(jsValue) => jsValue.validate(reader) map { a => Future.successful(Right(a)) } recoverTotal { jsError => val msg = JsError.toJson(jsError).toString() errorHandler.onClientError(request, Status.BAD_REQUEST, msg) map Left.apply } } } }
Example 10
Source File: LoggingFilter.scala From HAT2.0 with GNU Affero General Public License v3.0 | 5 votes |
package org.hatdex.hat.utils import javax.inject.{ Inject, Singleton } import akka.stream.Materializer import com.nimbusds.jose.JWSObject import com.nimbusds.jwt.JWTClaimsSet import play.api.http.HttpErrorHandler import play.api.mvc.{ Filter, RequestHeader, Result } import play.api.{ Configuration, Logger } import scala.concurrent.{ ExecutionContext, Future } import scala.util.Try @Singleton class ActiveHatCounter() { // Careful! Mutable state private var count: Long = 0 def get(): Long = count def increase(): Unit = this.synchronized(count += 1) def decrease(): Unit = this.synchronized(count -= 1) } class LoggingFilter @Inject() ( errorHandler: HttpErrorHandler, configuration: Configuration, hatCounter: ActiveHatCounter)( implicit ec: ExecutionContext, val mat: Materializer) extends Filter { private val logger = Logger("api") def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = { val startTime = System.currentTimeMillis nextFilter(requestHeader) .recoverWith({ case e ⇒ errorHandler.onServerError(requestHeader, e) }) .map { result => val active = hatCounter.get() val requestTime = System.currentTimeMillis - startTime logger.info(s"[${requestHeader.remoteAddress}] [${requestHeader.method}:${requestHeader.host}:${requestHeader.uri}] " + s"[${result.header.status}] [$requestTime:ms] [hats:$active] ${tokenInfo(requestHeader)}") result.withHeaders("Request-Time" -> requestTime.toString) } } private val authTokenFieldName: String = configuration.get[String]("silhouette.authenticator.fieldName") private def tokenInfo(requestHeader: RequestHeader): String = { requestHeader.queryString.get(authTokenFieldName).flatMap(_.headOption) .orElse(requestHeader.headers.get(authTokenFieldName)) .flatMap(t ⇒ if (t.isEmpty) { None } else { Some(t) }) .flatMap(t ⇒ Try(JWSObject.parse(t)).toOption) .map(o ⇒ JWTClaimsSet.parse(o.getPayload.toJSONObject)) .map { claimSet => s"[${Option(claimSet.getStringClaim("application")).getOrElse("api")}@" + s"${Option(claimSet.getStringClaim("applicationVersion")).getOrElse("_")}]" } .getOrElse("[unauthenticated@_]") } }
Example 11
Source File: ErrorHandler.scala From pujangga with Apache License 2.0 | 5 votes |
package services import scala.concurrent._ import javax.inject._ import play.api.http.HttpErrorHandler import play.api.libs.json._ import play.api.mvc.Results._ import play.api.mvc._ @Singleton class ErrorHandler extends HttpErrorHandler { def onClientError(request: RequestHeader, statusCode: Int, message: String) = { statusCode match { case 404 => Future.successful ( Status (statusCode) (Json.obj ("status" -> "error", "message" -> "Not Found") ) ) case _ => Future.successful ( Status (statusCode) (Json.obj ("status" -> "error", "message" -> message) ) ) } } def onServerError(request: RequestHeader, exception: Throwable) = { Future.successful( InternalServerError(Json.obj("status" -> "error", "message" -> exception.getMessage)) ) } }
Example 12
Source File: ErrorHandler.scala From asura with MIT License | 5 votes |
package asura.play.hook import asura.common.exceptions.ErrorMessages import asura.common.exceptions.ErrorMessages.ErrorMessageException import asura.common.model.{ApiCode, ApiRes, ApiResError} import asura.common.util.{LogUtils, StringUtils} import asura.play.api.BaseApi.OkApiRes import javax.inject.{Inject, Singleton} import org.slf4j.LoggerFactory import play.api.http.HttpErrorHandler import play.api.i18n.{Langs, MessagesApi} import play.api.mvc.{RequestHeader, Result} import scala.concurrent.Future @Singleton class ErrorHandler @Inject()(messagesApi: MessagesApi, langs: Langs) extends HttpErrorHandler with ErrorMessages { lazy val logger = LoggerFactory.getLogger(classOf[ErrorHandler]) override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = { val msg = s""""${request.method} ${request.uri}" ${statusCode} ${if (StringUtils.isNotEmpty(message)) message else ""}""" Future.successful(OkApiRes(ApiResError(msg))) } override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = { val logStack = LogUtils.stackTraceToString(exception) logger.warn(logStack) val requestLocal = request.headers.get("Local") implicit val lang = if (requestLocal.nonEmpty) { langs.availables.find(_.code == requestLocal.get).getOrElse(langs.availables.head) } else { langs.availables.head } exception match { case errMsgException: ErrorMessageException => val errMsg = messagesApi(errMsgException.error.name, errMsgException.error.errMsg) Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = errMsg, data = logStack))) case _ => val message = if (StringUtils.isNotEmpty(exception.getMessage)) { exception.getMessage } else { messagesApi(error_ServerError.name) } Future.successful(OkApiRes(ApiRes(code = ApiCode.ERROR, msg = message, data = logStack))) } } }
Example 13
Source File: HomeApi.scala From asura with MIT License | 5 votes |
package asura.app.api import asura.common.model.ApiRes import asura.core.es.model._ import asura.core.es.service.HomeService import asura.core.model.QueryHome import asura.play.api.BaseApi.OkApiRes import controllers.Assets import javax.inject.{Inject, Singleton} import org.pac4j.play.scala.SecurityComponents import play.api.http.HttpErrorHandler import play.api.mvc.{Action, AnyContent} import scala.concurrent.ExecutionContext @Singleton class HomeApi @Inject()( implicit exec: ExecutionContext, val controllerComponents: SecurityComponents, val assets: Assets, val errorHandler: HttpErrorHandler, ) extends BaseApi { def index() = assets.at("index.html") def asset(resource: String): Action[AnyContent] = { if (resource.startsWith("api") || resource.startsWith("openapi")) { Action.async(r => errorHandler.onClientError(r, NOT_FOUND, "Not found")) } else { if (resource.contains(".")) assets.at(resource) else index } } def query() = Action(parse.byteString).async { implicit req => val queryHome = req.bodyAs(classOf[QueryHome]) HomeService.queryDoc(queryHome).map(res => { OkApiRes(ApiRes(data = res.result.hits.hits.map(hit => { hit.sourceAsMap ++ Seq( (FieldKeys.FIELD__ID -> hit.id), ("_type" -> getDocType(hit.index)) ) }))) }) } private def getDocType(index: String): String = { index match { case Group.Index => "group" case Project.Index => "project" case RestApi.Index => "rest" case HttpCaseRequest.Index => "case" case DubboRequest.Index => "dubbo" case SqlRequest.Index => "sql" case Environment.Index => "env" case Scenario.Index => "scenario" case Job.Index => "job" case _ => index } } }
Example 14
Source File: ApiModule.scala From metronome with Apache License 2.0 | 5 votes |
package dcos.metronome package api import com.softwaremill.macwire._ import controllers.Assets import dcos.metronome.api.v0.controllers.ScheduledJobSpecController import dcos.metronome.api.v1.controllers._ import dcos.metronome.jobinfo.JobInfoService import dcos.metronome.jobrun.JobRunService import dcos.metronome.jobspec.JobSpecService import dcos.metronome.queue.LaunchQueueService import mesosphere.marathon.MetricsModule import mesosphere.marathon.core.auth.AuthModule import mesosphere.marathon.core.base.ActorsModule import mesosphere.marathon.core.election.ElectionService import mesosphere.marathon.core.plugin.PluginManager import mesosphere.marathon.metrics.Metrics import mesosphere.marathon.plugin.auth.{Authenticator, Authorizer} import play.api.http.HttpErrorHandler import play.api.mvc.ControllerComponents import play.api.routing.Router import router.Routes import scala.concurrent.ExecutionContext class ApiModule( controllerComponents: ControllerComponents, assets: Assets, httpErrorHandler: HttpErrorHandler, config: ApiConfig, jobSpecService: JobSpecService, jobRunService: JobRunService, jobInfoService: JobInfoService, pluginManager: PluginManager, launchQueueService: LaunchQueueService, actorsModule: ActorsModule, metricsModule: MetricsModule, electionService: ElectionService )(implicit ec: ExecutionContext) { lazy val authModule: AuthModule = new AuthModule(pluginManager) lazy val authorizer: Authorizer = authModule.authorizer lazy val authenticator: Authenticator = authModule.authenticator lazy val metrics: Metrics = metricsModule.metrics lazy val applicationController: ApplicationController = wire[ApplicationController] lazy val jobsSpecController: JobSpecController = wire[JobSpecController] lazy val jobRunsController: JobRunController = wire[JobRunController] lazy val jobSchedulerController: JobScheduleController = wire[JobScheduleController] lazy val scheduledJobSchedulerController: ScheduledJobSpecController = wire[ScheduledJobSpecController] lazy val launchQueueController: LaunchQueueController = wire[LaunchQueueController] lazy val router: Router = { // add the prefix string in local scope for the Routes constructor val prefix: String = "/" // scalafix:ok wire[Routes] } }
Example 15
Source File: ErrorHandler.scala From metronome with Apache License 2.0 | 5 votes |
package dcos.metronome package api import org.slf4j.LoggerFactory import play.api.http.HttpErrorHandler import play.api.http.Status._ import play.api.libs.json.Json import play.api.mvc.{RequestHeader, Result, Results} import play.twirl.api.HtmlFormat import scala.concurrent.Future class ErrorHandler extends HttpErrorHandler { private[this] val log = LoggerFactory.getLogger(getClass) override def onClientError(request: RequestHeader, statusCode: Int, message: String): Future[Result] = { log.debug(s"Client Error on path ${request.path}. Message: $message Status: $statusCode") val outputMessage = if (statusCode == NOT_FOUND) { ErrorHandler.noRouteHandlerMessage } else { message } val json = Json.obj("message" -> escape(outputMessage), "requestPath" -> escape(request.path)) Future.successful(Results.Status(statusCode)(json)) } override def onServerError(request: RequestHeader, exception: Throwable): Future[Result] = { private def escape(msg: String): String = HtmlFormat.escape(msg).body } object ErrorHandler { val noRouteHandlerMessage = "Unknown route." }