本文整理汇总了Scala中akka.http.scaladsl.server.ExceptionHandler类的典型用法代码示例。如果您正苦于以下问题:Scala ExceptionHandler类的具体用法?Scala ExceptionHandler怎么用?Scala ExceptionHandler使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ExceptionHandler类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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"))
})
}
示例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
}
}
示例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)
}
}
示例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.
}
}
示例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)
}
}
示例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)
}
}
示例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
}
示例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"
}
}
}
示例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")
}
}
}
示例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()
}
示例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"))
}
示例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)))
}
示例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)
}
}
示例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
}