当前位置: 首页>>代码示例>>Scala>>正文


Scala NonFatal类代码示例

本文整理汇总了Scala中scala.util.control.NonFatal的典型用法代码示例。如果您正苦于以下问题:Scala NonFatal类的具体用法?Scala NonFatal怎么用?Scala NonFatal使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NonFatal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: ProcessorHierarchySpec

//设置package包名称以及导入依赖的类
package akka.stream

import akka.stream.testkit.AkkaSpec
import akka.stream.scaladsl.Flow
import akka.actor.ActorContext
import scala.concurrent.Await
import scala.concurrent.duration._
import akka.actor.ActorRef
import scala.collection.immutable.TreeSet
import scala.util.control.NonFatal
import akka.stream.impl.ActorBasedFlowMaterializer

class ProcessorHierarchySpec extends AkkaSpec("akka.actor.debug.lifecycle=off\nakka.loglevel=INFO") {

  val materializer = FlowMaterializer(MaterializerSettings())

  def self = ActorBasedFlowMaterializer.currentActorContext().self

  "An ActorBasedFlowMaterializer" must {

    "generate the right level of descendants" in {
      val f = Flow(() ? {
        testActor ! self
        Flow(List(1)).map(x ? { testActor ! self; x }).toProducer(materializer)
      }).take(3).foreach(x ? {
        testActor ! self
        Flow(x).foreach(_ ? testActor ! self).consume(materializer)
      }).toFuture(materializer)
      Await.result(f, 3.seconds)
      val refs = receiveWhile(idle = 250.millis) {
        case r: ActorRef ? r
      }
      try {
        refs.toSet.size should be(8)
        refs.distinct.map(_.path.elements.size).groupBy(x ? x).mapValues(x ? x.size) should be(Map(2 -> 2, 3 -> 6))
      } catch {
        case NonFatal(e) ?
          println(refs.map(_.toString).to[TreeSet].mkString("\n"))
          throw e
      }
    }

  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:46,代码来源:ProcessorHierarchySpec.scala

示例2: interpret

//设置package包名称以及导入依赖的类
package org.atnos.eff

import cats._
import cats.implicits._

import scala.util.control.NonFatal


  def interpret[U](n: Eff[R, Unit] => Eff[U, Unit]): Last[U] =
    Last[U](value.map(v => v.map(n)))

  def interpretEff[U](n: Last[R] => Eff[U, Unit]): Last[U] =
    Last.eff(n(this))

  def <*(last: Last[R]): Last[R] =
    (value, last.value) match {
      case (None, None)       => this
      case (Some(r), None)    => this
      case (None, Some(l))    => last
      case (Some(r), Some(l)) => Last(Option(r *> l))
    }

  def *>(last: Last[R]): Last[R] =
    (value, last.value) match {
      case (None, None)       => this
      case (Some(r), None)    => this
      case (None, Some(l))    => last
      case (Some(r), Some(l)) => Last(Option(r *> l))
    }
}

object Last {

  def none[R]: Last[R] =
    Last(None)

  def eff[R](e: =>Eff[R, Unit]): Last[R] =
    Last(Option(Eval.later(evaluate(e))))

  def evaluate[R](e: =>Eff[R, Unit]): Eff[R, Unit] =
    try e
    catch { case NonFatal(t) =>
       if (sys.props.isDefinedAt("eff.debuglast"))
         println("executing one last eff action failed\n"+t.getStackTrace.mkString("\n"))
        Eff.pure[R, Unit](())
    }

} 
开发者ID:atnos-org,项目名称:eff,代码行数:49,代码来源:Last.scala

示例3: main

//设置package包名称以及导入依赖的类
package akka

import akka.actor.ActorSystem
import akka.actor.ExtendedActorSystem
import akka.actor.Actor
import akka.actor.Terminated
import akka.actor.ActorLogging
import akka.actor.Props
import akka.actor.ActorRef
import scala.util.control.NonFatal


  def main(args: Array[String]): Unit = {
    if (args.length != 1) {
      println("you need to provide exactly one argument: the class of the application supervisor actor")
    } else {
      val system = ActorSystem("Main")
      try {
        val appClass = system.asInstanceOf[ExtendedActorSystem].dynamicAccess.getClassFor[Actor](args(0)).get
        val app = system.actorOf(Props(appClass), "app")
        val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
      } catch {
        case NonFatal(e) ? system.shutdown(); throw e
      }
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app
    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:38,代码来源:Main.scala

示例4: JsonSchema

//设置package包名称以及导入依赖的类
package akka.http.documenteddsl.documentation

import org.coursera.autoschema.{AutoSchema, TypeMappings}
import play.api.libs.json.{JsObject, Json}

import scala.reflect.runtime.{universe => ru}
import scala.util.control.NonFatal

object JsonSchema {

  def resolveSchema[T](implicit t: ru.TypeTag[T], as: AutoSchema): JsObject = {
    try as.createSchema[T] catch {
      case NonFatal(err) =>
        def errPath(ex: Throwable): String = ex.getCause match {
          case null => ex.getMessage
          case x    => "[" + ex.getClass.getSimpleName + "]" + ex.getMessage + ". Caused by: " + errPath(x)
        }
        Json.obj("error" -> s"$t: ${errPath(err)}")
    }
  }

  val string: JsObject    = Json.obj("type" -> "string")
  val numeric: JsObject   = Json.obj("type" -> "number", "format" -> "number")
  val boolean: JsObject   = Json.obj("type" -> "boolean")
}

trait DocumentedTypeMappings extends TypeMappings {
  import JsonSchema._

  override def schemaTypeForScala(typeName: String): Option[JsObject] = {
    schemaTypes.get(typeName)
  }

  private val schemaTypes = Map(
    "scala.Nothing"           -> Json.obj(),
    "scala.Unit"              -> Json.obj(),
    "org.joda.time.DateTime"  -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.ZonedDateTime" -> Json.obj("type" -> "string", "format" -> "date"),
    "java.time.LocalDate"     -> Json.obj("type" -> "string", "format" -> "date", "pattern" -> localDatePattern),
    "java.util.Date"          -> Json.obj("type" -> "string", "format" -> "date"),
    "java.lang.String"        -> string,
    "scala.Boolean"           -> boolean,
    "scala.Int"               -> numeric,
    "scala.Long"              -> numeric,
    "scala.Double"            -> numeric,
    "scala.math.BigInt"       -> numeric,
    "scala.math.BigDecimal"   -> numeric,
    "java.util.UUID"          -> Json.obj("type" -> "string", "pattern" -> "^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$")
  )

  lazy val localDatePattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$"
}

object DocumentedTypeMappings extends DocumentedTypeMappings 
开发者ID:evolution-gaming,项目名称:akka-http-documenteddsl,代码行数:55,代码来源:JsonSchema.scala

示例5: ExecutionContextBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutionContextBackboneCoordinator[DA](backbone: Backbone[DA], executionContext: ExecutionContext) {

  import ExecutionContextBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    Future {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }(executionContext)
  }

}

object ExecutionContextBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:37,代码来源:ExecutionContextBackboneCoordinator.scala

示例6: ExecutorServiceBackboneCoordinator

//设置package包名称以及导入依赖的类
package ie.zalando.pipeline.backbone.concurrent

import java.util.concurrent.{ Callable, Future, ExecutorService }

import scala.util.Try
import scala.util.control.NonFatal

import org.slf4j.LoggerFactory

import cats.data.Xor
import ie.zalando.pipeline.backbone.Backbone
import ie.zalando.pipeline.backbone.Phases.{ LocalReleasePhase, TransformationPipelineFailure }

class ExecutorServiceBackboneCoordinator[DA](backbone: Backbone[DA], executor: ExecutorService) {
  import ExecutorServiceBackboneCoordinator._

  val localInitPhases = backbone.initializeTopLevelContexts

  private class BackboneCallable(datum: DA) extends Callable[Xor[TransformationPipelineFailure, DA]] {
    override def call(): Xor[TransformationPipelineFailure, DA] = {
      val (dataPhases, releasePhases) = backbone.initializeInLocalContext(-1, localInitPhases).unzip
      try {
        backbone.transformDatum(backbone.createStateMonad(dataPhases), datum)
      } finally {
        releasePhases.foreach((phase: LocalReleasePhase) => {
          Try({ phase.releaseLocalResources() }).recover { case NonFatal(ex) => log.warn(s"Release phase $phase failed:", ex) }
        })
      }
    }
  }

  def process(datum: DA): Future[Xor[TransformationPipelineFailure, DA]] = {
    executor.submit(new BackboneCallable(datum))
  }

}

object ExecutorServiceBackboneCoordinator {
  val log = LoggerFactory.getLogger(classOf[ExecutorServiceBackboneCoordinator[_]])
} 
开发者ID:retnuh,项目名称:pipeline-backbone,代码行数:41,代码来源:ExecutorServiceBackboneCoordinator.scala

示例7: RobotsTxtLookUp

//设置package包名称以及导入依赖的类
package bridgeapp.crawler

import java.net.URI

import akka.actor.{ActorRef, ActorSystem, Cancellable}
import bridgeapp.crawler.execution._
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.duration._
import scala.util.control.NonFatal


class RobotsTxtLookUp(throttling: ActorRef) extends Runnable with LazyLogging {
  override def run(): Unit = {
    logger.warn(s" Lookup robots.txt")
    val uri = new URI("https://rutracker.org/robots.txt")

    val parser = new ResponseParser {
      override def ->(response: Response): Unit = {
        val body = new String(response.body)
        Robots.parse(body) match {
          case Left(error) =>
            logger.error(s"Error parse robots txt file, $error ")
          case Right(robots) =>
            robots.nonGroupFields.map(s => (s.key, s.value)).toMap[String, String].get("Crawl-delay").fold() { delay =>
              try {
                val rate = Rate(1, delay.toFloat.second)
                throttling ! SetRate(rate)
              } catch {
                case NonFatal(e) => logger.error("Error parse crawl delay directive in robots.txt. ", e)
              }
            }
        }
      }
    }
    val request = Request(uri, parser)

    //throttling !! request
  }
}

class RobotsTXTScheduleExecutor(robotsTxtLookUp: RobotsTxtLookUp)(implicit val actorSystem: ActorSystem) {

  private implicit val prep = actorSystem.dispatcher.prepare()

  private var instance: Cancellable = _

  def execute(duration: FiniteDuration) = {
    instance = actorSystem.scheduler.schedule(duration, duration, robotsTxtLookUp)
  }

  def cancel(): Unit = {
    instance.cancel()
  }
} 
开发者ID:bridge-app,项目名称:crawler,代码行数:56,代码来源:RobotsTxtLookUp.scala

示例8: 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

示例9: futuristicErrors

//设置package包名称以及导入依赖的类
package akka_in_action.future

import akka.actor.ActorSystem

import scala.concurrent._
import scala.util.{Success, Failure}
import scala.util.control.NonFatal

object futuristicErrors extends App {
  implicit val system = ActorSystem()
  import system.dispatcher

  val futureFail = future {
    throw new Exception("Error!")
  }

  futureFail onComplete {
    case Failure(NonFatal(e)) => println(e)
    case Success(value) => println(value)
  }

  futureFail andThen {
    case _ => system.shutdown
  }
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:26,代码来源:futuristicErrors.scala

示例10: tryOnNextAndRequest

//设置package包名称以及导入依赖的类
package knot.core.emitters

import knot.core.Downstream
import knot.core.Signals.Request

import scala.util.control.NonFatal

trait RequestEimitter[T] {
  self: PartContext with RequestContext =>

  protected def tryOnNextAndRequest(part: Downstream[T], element: T, length: Long): Unit = {
    _requested -= 1
    try {
      part.onNext(element)
    } catch {
      case NonFatal(e) => error(e)
    }
    try part.request() catch {
      case NonFatal(e) => error(e)
    }
  }

  protected def emittRequest(length: Long): Unit = {
    if (input != null && _requested <= 0) {
      input.send(Request(length))
      _requested += length
      if (_requested < 0L)
        _requested = Long.MaxValue
    }
  }
} 
开发者ID:defvar,项目名称:knot,代码行数:32,代码来源:RequestEimitter.scala

示例11: DecryptConfig

//设置package包名称以及导入依赖的类
package com.evolutiongaming.crypto

import com.typesafe.config.{Config, ConfigFactory}
import scala.util.control.NonFatal

object DecryptConfig {
  def apply(password: String, config: Config = ConfigFactory.load()): String = try {
    if (config getBoolean "encryptedPasswords") {
      val secret = config getString "application.secret"
      Crypto.decryptAES(password, secret.substring(0, 16))
    } else {
      password
    }
  } catch {
    case NonFatal(e) => password
  }
} 
开发者ID:evolution-gaming,项目名称:crypto,代码行数:18,代码来源:DecryptConfig.scala

示例12: ClientMain

//设置package包名称以及导入依赖的类
package nl.dykam.hangman.client

import akka.actor._
import com.typesafe.config.{Config, ConfigFactory}
import nl.dykam.hangman.client.actors.Client

import scala.collection.JavaConverters._
import scala.util.control.NonFatal

object ClientMain {
  def main(args: Array[String]): Unit = {
    val baseConfig: Config = ConfigFactory.load()
    val config = ConfigFactory.parseMap(Map(
      "akka" -> Map(
        "cluster.roles" -> Map("0" -> "client").asJava
      ).asJava
    ).asJava).withFallback(baseConfig)

    val system = ActorSystem("NetTag", config)
    try {
      val app = system.actorOf(Props[Client], name = "client")

      val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
    } catch {
      case NonFatal(e) ? system.shutdown(); throw e
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app

    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:Dykam,项目名称:scala-akka-cluster-hangman,代码行数:40,代码来源:ClientMain.scala

示例13: SeedMain

//设置package包名称以及导入依赖的类
package nl.dykam.hangman.seed

import java.net.URI

import akka.actor._
import com.typesafe.config.{Config, ConfigFactory}
import nl.dykam.hangman.seed.actors.Seed

import scala.collection.JavaConversions._
import scala.collection.JavaConverters._
import scala.util.control.NonFatal

object SeedMain {
  def main(args: Array[String]): Unit = {
    val baseConfig: Config = ConfigFactory.load()
    val seedRawUrl: String = baseConfig.getStringList("akka.cluster.seed-nodes")(0)
    val seedUrl = new URI(seedRawUrl)

    val config = ConfigFactory.parseMap(Map(
      "akka" -> Map(
        "remote.netty.tcp.port" -> seedUrl.getPort,
        "cluster.roles" -> Map("0" -> "backend").asJava
      ).asJava
    ).asJava).withFallback(baseConfig)

    val system = ActorSystem("NetTag", config)
    try {
      val app = system.actorOf(Props[Seed], name = "seed")

      val terminator = system.actorOf(Props(classOf[Terminator], app), "app-terminator")
    } catch {
      case NonFatal(e) ? system.shutdown(); throw e
    }
  }

  class Terminator(app: ActorRef) extends Actor with ActorLogging {
    context watch app

    def receive = {
      case Terminated(_) ?
        log.info("application supervisor has terminated, shutting down")
        context.system.shutdown()
    }
  }

} 
开发者ID:Dykam,项目名称:scala-akka-cluster-hangman,代码行数:47,代码来源:SeedMain.scala

示例14: PagerDutyAlerter

//设置package包名称以及导入依赖的类
package pagerduty

import io.circe.generic.auto._
import io.circe.syntax._
import okhttp3.{MediaType, OkHttpClient, Request, RequestBody}
import play.api.Logger

import scala.util.control.NonFatal

object PagerDutyAlerter {

  case class Context(url: String, serviceKey: String, enableAlerts: Boolean)

  case class AlertBody(service_key: String, event_type: String, description: String)

  val httpClient = new OkHttpClient()
  def apply(message: String, context: Context): Unit = {
    if (context.enableAlerts) {
      val alertBody = AlertBody(context.serviceKey, "trigger", message).asJson.toString()
      try {
        val request = new Request.Builder()
          .url(context.url)
          .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), alertBody))
          .build()

        val response = httpClient
          .newCall(request)
          .execute()

        response.code match {
          case 200 => Logger.info(s"Raised alert to pagerduty for : $message}")
          case _   => Logger.warn(s"Failed to raise pagerduty alert for: $message")

        }
        response.close()
      } catch {
        case NonFatal(e) =>
          Logger.warn(s"Unable to create PagerDuty incident for message $message")
      }
    } else ()
  }
} 
开发者ID:ovotech,项目名称:comms-template-manager,代码行数:43,代码来源:PagerDutyAlerter.scala

示例15: onShutdown

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.base

import java.util.concurrent.atomic.AtomicBoolean

import org.slf4j.LoggerFactory

import scala.util.control.NonFatal

trait ShutdownHooks {
  def onShutdown(block: => Unit): Unit

  def shutdown(): Unit

  def isShuttingDown: Boolean
}

object ShutdownHooks {
  def apply(): ShutdownHooks = new DefaultShutdownHooks
}

private[base] class BaseShutdownHooks extends ShutdownHooks {
  private[this] val log = LoggerFactory.getLogger(getClass)
  private[this] var shutdownHooks = List.empty[() => Unit]
  private[this] val shuttingDown = new AtomicBoolean(false)

  override def onShutdown(block: => Unit): Unit = {
    shutdownHooks +:= { () => block }
  }

  override def shutdown(): Unit = {
    shuttingDown.set(true)
    shutdownHooks.foreach { hook =>
      try hook()
      catch {
        case NonFatal(e) => log.error("while executing shutdown hook", e)
      }
    }
    shutdownHooks = Nil
  }

  override def isShuttingDown: Boolean = shuttingDown.get
}


private class DefaultShutdownHooks extends BaseShutdownHooks {
  Runtime.getRuntime.addShutdownHook(new Thread() {
    override def run(): Unit = {
      shutdown()
    }
  })
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:52,代码来源:ShutdownHooks.scala


注:本文中的scala.util.control.NonFatal类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。