本文整理汇总了Scala中akka.http.scaladsl.server.ExceptionHandler类的典型用法代码示例。如果您正苦于以下问题:Scala ExceptionHandler类的具体用法?Scala ExceptionHandler怎么用?Scala ExceptionHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExceptionHandler类的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: UsersProtonModule
//设置package包名称以及导入依赖的类
package proton.users
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import akka.stream.ActorMaterializer
import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import scaldi.{Injectable, Module, TypesafeConfigInjector}
import spray.json.{CompactPrinter, JsonPrinter}
import scala.concurrent.ExecutionContext
class UsersProtonModule(config: Config) extends Module {
bind[ExecutionContext] to scala.concurrent.ExecutionContext.Implicits.global
bind[ActorSystem] to ActorSystem("ProtonUsers", config) destroyWith (_.terminate())
bind[JsonPrinter] to CompactPrinter
}
object UsersProtonApp extends App with Injectable with LazyLogging with SprayJsonSupport with UsersProtocol {
ProtonConfig.parse("users-dev.conf", args).foreach(c => {
val config = c.config
implicit val injector = TypesafeConfigInjector(config) :: new UsersProtonModule(config)
implicit val executionContext = inject[ExecutionContext]
implicit val system = inject[ActorSystem]
implicit val materializer = ActorMaterializer()
implicit val printer = inject[JsonPrinter]
implicit val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error("HTTP unhandled exception.", e)
var message = "HTTP unhandled exception."
if (e != null) {
message = e.getMessage
}
complete(InternalServerError -> Message(message, UsersEvents.Unhandled))
}
def route: Route =
pathSingleSlash {
get {
complete("test")
}
}
Http().bindAndHandle(route, config.getString("proton.ip"), config.getInt("proton.users.http.port"))
})
}
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:52,代码来源:UsersProtonApp.scala
示例2: Api
//设置package包名称以及导入依赖的类
package com.durooma.api.route
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.ExceptionHandler
import com.durooma.api.error.AuthenticationError
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
object Api extends CustomDirectives with JsonSupport {
val genericExceptionHandler = ExceptionHandler {
case AuthenticationError(message) => complete((StatusCodes.Unauthorized, message))
case e: MySQLIntegrityConstraintViolationException => e.getErrorCode match {
case 1062 => complete((StatusCodes.BadRequest, e.getMessage))
}
case e =>
e.printStackTrace()
complete((StatusCodes.InternalServerError, e.getLocalizedMessage))
}
val route = handleExceptions(genericExceptionHandler) {
AccountResource.route ~
TransactionResource.route ~
UserResource.route ~
SessionResource.route
}
}
开发者ID:durooma,项目名称:api,代码行数:29,代码来源:Api.scala
示例3: CustomExceptionHandling
//设置package包名称以及导入依赖的类
package com.queirozf.utils
import java.time.format.DateTimeParseException
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import com.queirozf.utils.ResponseUtils._
import org.slf4j.LoggerFactory
import scala.util.control.NonFatal
object CustomExceptionHandling {
private val logger = LoggerFactory.getLogger("balance-tracker.errors")
def handler = ExceptionHandler {
case dpe: DateTimeParseException => complete(JsonError(dpe))
case NonFatal(nf) => {
logger.error("Non-fatal error thrown: ", nf)
// avoid leaking information
complete(JsonError(new Exception("An unexpected error occurred.")))
}
case t: Throwable => {
logger.error("Fatal error thrown: ", t)
complete(JsonError(new Exception("An unexpected error occurred.")))
}
}
}
开发者ID:queirozfcom,项目名称:akka-http-docker-aws-code-pipeline-beanstalk,代码行数:31,代码来源:CustomExceptionHandling.scala
示例4: Failure
//设置package包名称以及导入依赖的类
package com.shashank.akkahttp.basic.routing
import akka.actor.ActorSystem
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.stream.{ActorMaterializer, Materializer}
object Failure {
def main(args: Array[String]) {
implicit val sys = ActorSystem("IntroductionToAkkaHttp")
implicit val mat:Materializer = ActorMaterializer()
implicit def myExceptionHandler = ExceptionHandler {
case _: ArithmeticException =>
complete(HttpResponse(StatusCodes.BadRequest, entity = "Bad numbers, bad result!!!"))
case e: Throwable => {
println(e.getMessage)
println(e.getStackTraceString)
complete(HttpResponse(StatusCodes.BadRequest, entity = e.getMessage))
}
}
val route =
path("welcome"){
get{
complete {
"welcome to rest service"
}
}
} ~
path("demo"){
get {
complete {
100/0
"welcome to demonstration"
}
}
}
Http().bindAndHandle(route, "localhost", 8090)
}
}
开发者ID:shashankgowdal,项目名称:introduction-to-akkahttp,代码行数:50,代码来源:Failure.scala
示例5: Router
//设置package包名称以及导入依赖的类
package gateway.restapi.http
import akka.event.LoggingAdapter
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route}
import akka.stream.ActorMaterializer
import scala.concurrent.ExecutionContext
import gateway.restapi.http.routes.{ClientsServiceRoute, GatewayRoute}
import gateway.restapi.utils.CorsSupport
class Router(clientsRouter: ClientsServiceRoute, gatewayRouter: GatewayRoute)
(implicit executionContext: ExecutionContext, log: LoggingAdapter, materializer : ActorMaterializer) extends CorsSupport {
def BuildRoute: Route = {
val exceptionHandler = ExceptionHandler { // todo: response with internal exception message in DEBUG only
case error: Throwable => { // not a bad practice to catch Throwable here because it's the Root
log.error(error, error.getMessage)
extractUri { uri =>
complete(HttpResponse(StatusCodes.BadRequest, entity = error.getMessage))
}
}
}
logRequestResult("gateway-sketch-rest-api") {
handleExceptions(exceptionHandler) {
pathPrefix("v1") {
corsHandler {
clientsRouter.route ~
gatewayRouter.route
}
}
} // Route.seal()
}
////A Route can be "sealed" using Route.seal, which relies on the in-scope RejectionHandler and
////ExceptionHandler instances to convert rejections and exceptions into appropriate HTTP responses for the client.
}
}
开发者ID:kartavtcev,项目名称:gateway-sketch,代码行数:39,代码来源:Router.scala
示例6: AdminExceptionHandler
//设置package包名称以及导入依赖的类
package csw.apps.clusterseed.admin.http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, ExceptionHandler}
import csw.apps.clusterseed.admin.exceptions.UnresolvedAkkaLocationException
import csw.apps.clusterseed.commons.ClusterSeedLogger
import scala.util.control.NonFatal
class AdminExceptionHandler extends Directives with ClusterSeedLogger.Simple {
val exceptionHandler: ExceptionHandler = ExceptionHandler {
case ex: UnresolvedAkkaLocationException ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.NotFound ? ex.getMessage)
case NonFatal(ex) ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.InternalServerError ? ex.getMessage)
}
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:22,代码来源:AdminExceptionHandler.scala
示例7: ConfigExceptionHandler
//设置package包名称以及导入依赖的类
package csw.services.config.server.http
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.{Directives, ExceptionHandler}
import csw.services.config.api.exceptions.{FileAlreadyExists, FileNotFound, InvalidInput}
import csw.services.config.server.commons.ConfigServerLogger
import scala.util.control.NonFatal
class ConfigExceptionHandler extends Directives with ConfigServerLogger.Simple {
val exceptionHandler: ExceptionHandler = ExceptionHandler {
case ex: FileAlreadyExists ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.Conflict ? ex.getMessage)
case ex: FileNotFound ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.NotFound ? ex.getMessage)
case ex: InvalidInput ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.BadRequest ? ex.getMessage)
case NonFatal(ex) ?
log.error(ex.getMessage, ex = ex)
complete(StatusCodes.InternalServerError ? ex.getMessage)
}
}
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:28,代码来源:ConfigExceptionHandler.scala
示例8:
//设置package包名称以及导入依赖的类
package com.acromancer.acromancer.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport
with SecuritySupport
with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:GitsAndGlamour,项目名称:acromancer-game,代码行数:35,代码来源:RoutesRequestWrapper.scala
示例9:
//设置package包名称以及导入依赖的类
package com.packt.chapter9
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.pattern.AskTimeoutException
trait RouteExceptionHandler {
val routeExceptionHandler = ExceptionHandler {
case _: ArithmeticException =>
complete {
StatusCodes.BadRequest -> "You values are incorrect. Probably b needs to be different from 0"
}
case _: AskTimeoutException =>
complete {
StatusCodes.ServiceUnavailable -> "Internal actor is not responding within 500 millis"
}
}
}
开发者ID:PacktPublishing,项目名称:Akka-Cookbook,代码行数:21,代码来源:RouteExceptionHandler.scala
示例10: Server
//设置package包名称以及导入依赖的类
package com.ulasakdeniz.hakker
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, RouteResult}
import com.typesafe.config.{Config, ConfigFactory}
import scala.util.Try
class Server(configOpt: Option[Config] = None) extends System with Logger[Server] {
val config: Config = {
val configName = "hakker"
lazy val defaultConfig = ConfigFactory.load(configName).getConfig(configName)
configOpt
.flatMap(cfg => {
Try(cfg.getConfig(configName)).toOption.map(hakkerConfig =>
hakkerConfig.withFallback(defaultConfig))
})
.getOrElse {
log.warning(
"Missing \"hakker\" field in the configuration file, " +
"default configuration will be used.")
defaultConfig
}
}
val exceptionHandler: ExceptionHandler = ExceptionHandler {
case ex: Exception =>
extractUri { uri =>
log.error(ex, "Request to {} could not be handled normally", uri)
complete(HttpResponse(InternalServerError))
}
}
def run(routeHandler: Route): Unit = {
val defaultPort = 8080
val interface: String = Try(config.getString("interface")).getOrElse("localhost")
val port: Int = Try(config.getInt("port")).getOrElse(defaultPort)
val routes: Route = handleExceptions(exceptionHandler)(routeHandler)
val bindingFuture = http.bindAndHandle(RouteResult.route2HandlerFlow(routes), interface, port)
log.info("Server online at http://{}:{}", interface, port)
bindingFuture
.map(binding => {
sys.addShutdownHook(binding.unbind())
})
.recover { case ex: Exception => log.error("Failed to bind!") }
sys.addShutdownHook {
system.terminate()
log.info("Actor System terminated")
}
}
}
开发者ID:ulasakdeniz,项目名称:hakker,代码行数:59,代码来源:Server.scala
示例11: exceptionHandler
//设置package包名称以及导入依赖的类
package com.peim.utils
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, MethodRejection, RejectionHandler, ValidationRejection}
import com.peim.model.exception.MoneyServiceException
import com.peim.model.response.ErrorResponse
import play.api.libs.json.Json
trait ExceptionHandlers {
implicit def exceptionHandler: ExceptionHandler =
ExceptionHandler {
case e: MoneyServiceException =>
extractUri { uri =>
val errorResponse = ErrorResponse(Conflict.intValue,
"Conflict", e.getMessage)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(Conflict, entity = entity))
}
case e: Exception =>
extractUri { uri =>
val errorResponse = ErrorResponse(InternalServerError.intValue,
"Internal Server Error", e.getMessage)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(InternalServerError, entity = entity))
}
}
implicit def rejectionHandler: RejectionHandler =
RejectionHandler.newBuilder()
.handleNotFound {
val errorResponse = ErrorResponse(NotFound.intValue,
"NotFound", "The requested resource could not be found.")
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(NotFound, entity = entity))
}
.handle { case ValidationRejection(message, _) =>
val errorResponse = ErrorResponse(BadRequest.intValue, "Bad Request", message)
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(BadRequest, entity = entity)) }
.handleAll[MethodRejection] { methodRejections =>
val names = methodRejections.map(_.supported.name)
val errorResponse = ErrorResponse(MethodNotAllowed.intValue,
"Not Allowed", s"Access to $names is not allowed.")
val entity = HttpEntity(ContentTypes.`application/json`, Json.toJson(errorResponse).toString)
complete(HttpResponse(MethodNotAllowed, entity = entity))
}
.result()
}
开发者ID:peim,项目名称:money-transfer-service,代码行数:52,代码来源:ExceptionHandlers.scala
示例12: executor
//设置package包名称以及导入依赖的类
package zeroweather.proxy
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import akka.stream.{ ActorMaterializer, Materializer }
import spray.json._
import zeroweather.message.Weather
import scala.concurrent.ExecutionContextExecutor
trait Protocols extends DefaultJsonProtocol {
implicit val weatherFormat = jsonFormat4(Weather.apply)
}
trait ProxyService extends Protocols {
implicit val system: ActorSystem
implicit def executor: ExecutionContextExecutor
implicit val materializer: Materializer
val supplierConnector: SupplierConnector
implicit def exceptionHandler = ExceptionHandler {
case e: java.io.IOException =>
extractUri { uri =>
complete(HttpResponse(ServiceUnavailable, entity = e.getMessage))
}
}
val routes = {
pathPrefix("weather" / """[a-z]{2}""".r / """[a-zA-Z ]+""".r) { (countryCode, city) =>
pathEnd {
get {
complete {
supplierConnector.fetchWeather(countryCode, city).map[ToResponseMarshallable] {
case Right(weather) => weather
case Left(error) => BadRequest -> error
}
}
}
}
}
}
}
object Proxy extends App with ProxyService with Supplier with Configuration {
override implicit val system = ActorSystem("Proxy")
override implicit val executor = system.dispatcher
override implicit val materializer = ActorMaterializer()
Http().bindAndHandle(routes, config.getString("http.interface"), config.getInt("http.port"))
}
开发者ID:sbilinski,项目名称:zeroweather,代码行数:58,代码来源:Proxy.scala
示例13: nothingHere
//设置package包名称以及导入依赖的类
package au.edu.utscic.athanorserver.server
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route, StandardRoute}
import au.edu.utscic.athanorserver.message.Exception.UnknownAnalysisType
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
//noinspection ForwardReference
trait GenericApi extends Json4sSupport {
import au.edu.utscic.athanorserver.StreamsContext._
val version = "v2"
val details:String = "no details yet" // ApiInfo(Config.name,Config.description,Config.version,Config.colour)
val healthEndPoint = "health"
val athanorExceptionHandler = ExceptionHandler {
case _: UnknownAnalysisType =>
extractUri { uri =>
log.error(s"Request to $uri did not include a valid analysis type")
complete(HttpResponse(InternalServerError, entity = "The request did not include a valid analysis type"))
}
}
implicit val formats: Formats = DefaultFormats
implicit val jacksonSerialization: Serialization = jackson.Serialization
def nothingHere: StandardRoute = complete(ResponseMessage("There is nothing at this URL"))
val routes: Route = handleExceptions(athanorExceptionHandler) {
pathSingleSlash {
get(complete(ResponseMessage("The current version of this API can be found at /"+version)))
} ~
pathPrefix(version) {
customRoutes ~
path(healthEndPoint) {
get(complete(ResponseMessage("ok")))
} ~
apiDetails ~
adminRoutes
}
}
val customRoutes: Route = path("custom") { get(complete("")) }
val adminRoutes: Route = path("admin") { get(complete(""))}
val apiDetails: Route = pathEnd(complete(ResponseMessage(details)))
}
开发者ID:uts-cic,项目名称:athanor-server,代码行数:52,代码来源:GenericApi.scala
示例14: exceptionHandler
//设置package包名称以及导入依赖的类
package com.lonelyplanet.akka.http.extensions
import akka.http.scaladsl.server.ExceptionHandler
import com.lonelyplanet.akka.http.extensions.exceptions.ResourceNotFound
import com.lonelyplanet.util.AirbrakeService
trait ExceptionHandlingWithAirbrake extends ExceptionHandling {
val airbrakeService: AirbrakeService
override implicit def exceptionHandler: ExceptionHandler = ExceptionHandler {
case e: ResourceNotFound =>
super.exceptionHandler.apply(e)
case e =>
airbrakeService.notify(e)
super.exceptionHandler.apply(e)
}
}
开发者ID:lonelyplanet,项目名称:akka-http-extensions,代码行数:18,代码来源:ExceptionHandlingWithAirbrake.scala
示例15: recordResponseTime
//设置package包名称以及导入依赖的类
package com.lonelyplanet.prometheus.directives
import akka.http.scaladsl.server.ExceptionHandler
import akka.http.scaladsl.server.directives.{BasicDirectives, ExecutionDirectives}
import com.lonelyplanet.prometheus.ResponseTimeRecorder
import scala.concurrent.duration
import scala.concurrent.duration.FiniteDuration
import scala.util.control.NonFatal
trait ResponseTimeRecordingDirectives {
this: ResponseTimeRecorderProvider =>
def recordResponseTime(endpoint: String) = BasicDirectives.extractRequestContext.flatMap { ctx =>
val requestStartTime = System.nanoTime()
BasicDirectives.mapResponse { resp =>
record(endpoint, requestStartTime)
resp
} & ExecutionDirectives.handleExceptions {
responseTimeRecordingExceptionHandler(endpoint, requestStartTime)
}
}
private def responseTimeRecordingExceptionHandler(endpoint: String, requestStartTime: Long) = ExceptionHandler {
case NonFatal(e) =>
record(endpoint, requestStartTime)
// Rethrow the exception to allow proper handling
// from handlers higher ip in the hierarchy
throw e
}
private def record(endpoint: String, requestStartTime: Long): Unit = {
val requestEndTime = System.nanoTime()
val total = new FiniteDuration(requestEndTime - requestStartTime, duration.NANOSECONDS)
recorder.recordResponseTime(endpoint, total)
}
}
object ResponseTimeRecordingDirectives {
def apply(r: ResponseTimeRecorder) = {
new ResponseTimeRecordingDirectives with ResponseTimeRecorderProvider {
override def recorder: ResponseTimeRecorder = r
}
}
}
trait ResponseTimeRecorderProvider {
def recorder: ResponseTimeRecorder
}
开发者ID:lonelyplanet,项目名称:prometheus-akka-http,代码行数:53,代码来源:ResponseTimeRecordingDirectives.scala
示例16:
//设置package包名称以及导入依赖的类
package com.softwaremill.bootzooka.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport with SecuritySupport with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:Bii03,项目名称:students-clustering,代码行数:33,代码来源:RoutesRequestWrapper.scala
示例17: nothingHere
//设置package包名称以及导入依赖的类
package au.edu.utscic.tap.httpServer
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.ExceptionHandler
import au.edu.utscic.tap.message.Exception.UnknownAnalysisType
import de.heikoseeberger.akkahttpjson4s.Json4sSupport
import org.json4s._
trait GenericApi extends Json4sSupport {
import au.edu.utscic.tap.TapStreamContext._
val version = "v2"
val details:String = "no details yet" // ApiInfo(Config.name,Config.description,Config.version,Config.colour)
val healthEndPoint = "health"
val TapExceptionHandler = ExceptionHandler {
case _: UnknownAnalysisType =>
extractUri { uri =>
log.error(s"Request to $uri did not include a valid analysis type")
complete(HttpResponse(InternalServerError, entity = "The request did not include a valid analysis type"))
}
}
implicit val formats: Formats = DefaultFormats
implicit val jacksonSerialization: Serialization = jackson.Serialization
def nothingHere = complete(ResponseMessage("There is nothing at this URL"))
val routes = handleExceptions(TapExceptionHandler) {
pathSingleSlash {
get(complete(ResponseMessage("The current version of this API can be found at /"+version)))
} ~
pathPrefix(version) {
customRoutes ~
path(healthEndPoint) {
get(complete(ResponseMessage("ok")))
} ~
apiDetails ~
adminRoutes
}
}
val customRoutes = path("custom") { get(complete("")) }
val adminRoutes = path("admin") { get(complete(""))}
val apiDetails = pathEnd(complete(ResponseMessage(details)))
}
开发者ID:uts-cic,项目名称:tap-api,代码行数:53,代码来源:GenericApi.scala
示例18:
//设置package包名称以及导入依赖的类
package northendlink.common.api
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, RejectionHandler}
import com.typesafe.scalalogging.StrictLogging
trait RoutesRequestWrapper extends CacheSupport
with SecuritySupport
with StrictLogging {
private val exceptionHandler = ExceptionHandler {
case e: Exception =>
logger.error(s"Exception during client request processing: ${e.getMessage}", e)
_.complete(StatusCodes.InternalServerError, "Internal server error")
}
private val rejectionHandler = RejectionHandler.default
private val logDuration = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
// handling rejections here so that we get proper status codes
mapResponse { resp =>
val d = System.currentTimeMillis() - start
logger.info(s"[${resp.status.intValue()}] ${ctx.request.method.name} ${ctx.request.uri} took: ${d}ms")
resp
} & handleRejections(rejectionHandler)
}
val requestWrapper = logDuration &
handleExceptions(exceptionHandler) &
cacheImages &
addSecurityHeaders &
encodeResponse
}
开发者ID:OOSINT,项目名称:NorthendLink-Site,代码行数:35,代码来源:RoutesRequestWrapper.scala
示例19: myExceptionHandler
//设置package包名称以及导入依赖的类
package com.codebook.akka.route
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{ExceptionHandler, Route}
trait ErrorHandler {
implicit def myExceptionHandler = ExceptionHandler {
case e: NoSuchElementException =>
extractUri { uri =>
complete(HttpResponse(NotFound, entity = s"Invalid id: ${e.getMessage}"))
}
}
}
trait Routes extends ErrorHandler with SysRoute with UserRoute with UrlRoute with StocksRoute {
val index = "public/index.html"
val root = ""
val sys = "sys"
val api = "api"
def routes: Route =
logRequestResult("akka-services") {
path(root)(getFromResource(index)) ~
pathPrefix(sys)(sysRoute) ~
pathPrefix(api)(userRoute ~ urlRoute ~ stocksRoute)
}
}
开发者ID:flopezlasanta,项目名称:akka-services,代码行数:31,代码来源:Routes.scala
注:本文中的akka.http.scaladsl.server.ExceptionHandler类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论