本文整理汇总了Scala中scala.util.control.NoStackTrace类的典型用法代码示例。如果您正苦于以下问题:Scala NoStackTrace类的具体用法?Scala NoStackTrace怎么用?Scala NoStackTrace使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NoStackTrace类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: StdOutLogger
//设置package包名称以及导入依赖的类
package knot.core.logging
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import scala.util.control.NoStackTrace
object StdOutLogger {
final val errorLevel = 1
final val warningLevel = 2
final val infoLevel = 3
final val debugLevel = 4
}
case class StdOutLogger(name: String, logLevel: Int = 1) extends Logger {
override def isErrorEnabled: Boolean = logLevel >= StdOutLogger.errorLevel
override def isWarningEnabled: Boolean = logLevel >= StdOutLogger.warningLevel
override def isInfoEnabled: Boolean = logLevel >= StdOutLogger.infoLevel
override def isDebugEnabled: Boolean = logLevel >= StdOutLogger.debugLevel
override protected def logError(cause: Throwable, message: String): Unit = {
println(s"$time [ERROR] - $thread - $name - $message ${stackTrace(cause)}")
}
override protected def logWarning(message: String): Unit = {
println(s"$time [WARN ] - $thread - $name - $message")
}
override protected def logInfo(message: String): Unit = {
println(s"$time [INFO ] - $thread - $name - $message")
}
override protected def logDebug(message: String): Unit = {
println(s"$time [DEBUG] - $thread - $name - $message")
}
private def time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)
private def thread = Thread.currentThread.getName
private def stackTrace(e: Throwable): String = e match {
case null => ""
case _: NoStackTrace => " (" + e.getClass.getName + ")"
case other =>
val sw = new java.io.StringWriter
val pw = new java.io.PrintWriter(sw)
pw.append('\n')
other.printStackTrace(pw)
sw.toString
}
}
示例2: HTTPException
//设置package包名称以及导入依赖的类
package run.cosy.solid.client
import org.w3.banana.jena.Jena.Rdf
import scala.util.control.NoStackTrace
trait WebException extends java.lang.RuntimeException with NoStackTrace with Product with Serializable
case class HTTPException(
response: ResponseSummary, msg: String,
history: List[ResponseSummary]=List()
) extends WebException
case class AuthException(
response: ResponseSummary, msg: String,
history: List[ResponseSummary]=List()
) extends WebException
case class StatusCodeException(
response: ResponseSummary,
history: List[ResponseSummary]=List()
) extends WebException
case class ConnectionException(
resourceUri: String, e: Throwable,
history: List[ResponseSummary]=List()
) extends WebException
case class NodeTranslationException(
graphLoc: String, problemNode: Rdf#Node, e: Throwable,
history: List[ResponseSummary]=List()
) extends WebException
case class MissingParserException(
response: ResponseSummary,
initialContent: String,
history: List[ResponseSummary]=List()
) extends WebException
case class ParseException(
response: ResponseSummary,
initialContent: String,
e: Throwable,
history: List[ResponseSummary]=List()
) extends WebException
case class LogException(
history: List[ResponseSummary],
e: Throwable)
示例3: details
//设置package包名称以及导入依赖的类
package com.snapswap.db.errors
import scala.util.control.NoStackTrace
trait DataError extends NoStackTrace {
def details: String
def dbDetails: Option[String] = None
override def getMessage: String = dbDetails match {
case None =>
details
case Some(d) =>
s"$details\n$d"
}
}
示例4: ConnektException
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.busybees.streams.errors
import scala.util.control.NoStackTrace
class ConnektException(message: String, cause: Throwable = null) extends RuntimeException(message, cause) with NoStackTrace
case class ConnektPNStageException(messageId: String,
client: String,
destinations: Set[String],
eventType: String,
appName: String,
platform: String,
context: String,
meta: Map[String, Any],
message: String,
cause: Throwable,
timeStamp: Long = System.currentTimeMillis()) extends ConnektException(message, cause)
case class ConnektStageException(messageId: String,
client: String,
destinations: Set[String],
eventType: String,
appName: String,
channel: String,
context: String,
meta: Map[String, Any],
message: String,
cause: Throwable,
timeStamp: Long = System.currentTimeMillis()) extends ConnektException(message, cause)
示例5: CompressionUtils
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.utils
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import java.util.Base64
import java.util.zip.{GZIPInputStream, GZIPOutputStream}
import com.flipkart.connekt.commons.core.Wrappers._
import org.apache.commons.io.IOUtils
import scala.util.Try
import scala.util.control.NoStackTrace
object CompressionUtils {
def inflate(deflatedTxt: String): Try[String] = Try_ {
val bytes = Base64.getUrlDecoder.decode(deflatedTxt)
try {
val zipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes))
IOUtils.toString(zipInputStream)
} catch {
case ex:java.util.zip.ZipException =>
throw new Exception(ex.getMessage) with NoStackTrace
}
}
def deflate(txt: String): Try[String] = Try_ {
val arrOutputStream = new ByteArrayOutputStream()
val zipOutputStream = new GZIPOutputStream(arrOutputStream)
zipOutputStream.write(txt.getBytes)
zipOutputStream.close()
Base64.getUrlEncoder.encodeToString(arrOutputStream.toByteArray)
}
implicit class StringCompress(val s: String) {
def compress: Try[String] = deflate(s)
def decompress: Try[String] = inflate(s)
}
}
示例6: InMemoryStoreService
//设置package包名称以及导入依赖的类
package service
import javax.inject.Singleton
import com.typesafe.scalalogging.StrictLogging
import model.domain.{Category, CategoryDistribution, StoreProduct}
import scala.collection.mutable.{Map => MutableMap}
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace
@Singleton
class InMemoryStoreService()(
implicit exec: ExecutionContext
) extends StoreFront with StrictLogging {
val productByTitle: MutableMap[String, StoreProduct] = MutableMap.empty
val productsByCategory: MutableMap[Category, List[StoreProduct]] = MutableMap.empty
override def productTitlesForCategory(category: String): Future[Set[String]] = {
productsByCategory.get(Category(category)) match {
case Some(products) => Future.successful(products.map(_.title).toSet)
case None => Future.failed(new Exception(s"Unrecognised category $category") with NoStackTrace)
}
}
override def addProduct(product: StoreProduct): Future[Unit] = synchronized {
productByTitle(product.title) = product
product.categories.values.foreach(cat => {
val list = productsByCategory.getOrElse(cat, Nil)
productsByCategory(cat) = product :: list
})
Future.successful(())
}
}
示例7: DatabaseProductService
//设置package包名称以及导入依赖的类
package service
import javax.inject.{Inject, Singleton}
import com.outworkers.phantom.dsl.context
import com.typesafe.scalalogging.StrictLogging
import model.db.ProdDb
import model.domain.{Category, CategoryDistribution, StoreProduct}
import play.api.Environment
import play.api.inject.ApplicationLifecycle
import scala.concurrent.{ExecutionContext, Future}
import scala.util.control.NoStackTrace
@Singleton
class DatabaseProductService @Inject()(
environment: Environment,
applicationLifecycle: ApplicationLifecycle
)(
implicit exec: ExecutionContext
) extends StoreFront with StrictLogging with ProdDb {
override def getProduct(title: String): Future[Option[StoreProduct]] = {
database.products.findByTitle(title)
}
override def addProductToCategory(title: String, category: Category): Future[Unit] = {
getProduct(title) flatMap {
case Some(product) =>
for {
cat <- database.productsByCategory.store(category, product)
prod <- database.products.addCategory(title, category)
} yield ()
case None => Future.failed(new Exception(s"Could not find product with title $title") with NoStackTrace)
}
}
override def addProduct(product: StoreProduct): Future[Unit] = {
for {
_ <- database.products.store(product)
cats <- Future.sequence(product.categories.values.map(c => database.productsByCategory.store(c, product)))
} yield ()
}
}
示例8: PlayJsonException
//设置package包名称以及导入依赖的类
package com.wavesplatform.http
import scala.util.control.Exception.nonFatalCatch
import scala.util.control.NoStackTrace
import akka.http.scaladsl.marshalling.{Marshaller, PredefinedToEntityMarshallers, ToEntityMarshaller, ToResponseMarshaller}
import akka.http.scaladsl.model.MediaTypes.{`application/json`, `text/plain`}
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.unmarshalling.{FromEntityUnmarshaller, PredefinedFromEntityUnmarshallers, Unmarshaller}
import akka.util.ByteString
import play.api.libs.json._
import scorex.api.http.ApiError
import scorex.transaction.{Transaction, ValidationError}
case class PlayJsonException(
cause: Option[Throwable] = None,
errors: Seq[(JsPath, Seq[JsonValidationError])] = Seq.empty) extends IllegalArgumentException with NoStackTrace
trait ApiMarshallers {
type TRM[A] = ToResponseMarshaller[A]
import akka.http.scaladsl.marshalling.PredefinedToResponseMarshallers._
implicit val aem: TRM[ApiError] = fromStatusCodeAndValue[StatusCode, JsValue].compose { ae => ae.code -> ae.json }
implicit val vem: TRM[ValidationError] = aem.compose(ve => ApiError.fromValidationError(ve))
implicit val tw: Writes[Transaction] = Writes(_.json)
private val jsonStringUnmarshaller =
Unmarshaller.byteStringUnmarshaller
.forContentTypes(`application/json`)
.mapWithCharset {
case (ByteString.empty, _) => throw Unmarshaller.NoContentException
case (data, charset) => data.decodeString(charset.nioCharset.name)
}
private lazy val jsonStringMarshaller =
Marshaller.stringMarshaller(`application/json`)
implicit def playJsonUnmarshaller[A](implicit reads: Reads[A]): FromEntityUnmarshaller[A] =
jsonStringUnmarshaller map { data =>
val json = nonFatalCatch.withApply(t => throw PlayJsonException(cause = Some(t)))(Json.parse(data))
json.validate[A] match {
case JsSuccess(value, _) => value
case JsError(errors) => throw PlayJsonException(errors = errors)
}
}
// preserve support for extracting plain strings from requests
implicit val stringUnmarshaller: FromEntityUnmarshaller[String] = PredefinedFromEntityUnmarshallers.stringUnmarshaller
implicit val intUnmarshaller: FromEntityUnmarshaller[Int] = stringUnmarshaller.map(_.toInt)
implicit def playJsonMarshaller[A](
implicit writes: Writes[A],
printer: JsValue => String = Json.prettyPrint): ToEntityMarshaller[A] =
jsonStringMarshaller.compose(printer).compose(writes.writes)
// preserve support for using plain strings as request entities
implicit val stringMarshaller = PredefinedToEntityMarshallers.stringMarshaller(`text/plain`)
}
object ApiMarshallers extends ApiMarshallers
示例9: ParseException
//设置package包名称以及导入依赖的类
package de.envisia.play.thrift.frontend
import scala.util.control.NoStackTrace
class ParseException(reason: String, cause: Throwable) extends Exception(reason, cause) with NoStackTrace{
def this(reason: String) = this(reason, null)
}
class FileParseException(filename: String, cause: Throwable)
extends ParseException("Exception parsing: %s".format(filename), cause)
// severe errors
class NegativeFieldIdException(name: String)
extends ParseException("Negative user-provided id in field " + name)
class DuplicateFieldIdException(name: String)
extends ParseException("Duplicate user-provided id in field " + name)
class RepeatingEnumValueException(name: String, value: Int)
extends ParseException("Repeating enum value in " + name + ": " + value)
class UnionFieldInvalidNameException(union: String, field: String)
extends ParseException("Field " + field + " in union " + union + " is prohibited")
// warnings (non-severe errors). If the strict mode is on, Scrooge will throw these exceptions;
// otherwise it merely prints warnings.
class ParseWarning(reason: String, cause: Throwable)
extends ParseException(reason, cause)
{
def this(reason: String) = this(reason, null)
}
class UnionFieldRequiredException(union: String, field: String)
extends ParseWarning("Field " + field + " in union " + union + " cannot be required")
class UnionFieldOptionalException(union: String, field: String)
extends ParseWarning("Field " + field + " in union " + union + " cannot be optional")
object UnionFieldRequirednessException {
def apply(union: String, field: String, requiredness: String): ParseWarning = {
requiredness.toLowerCase match {
case "required" => new UnionFieldRequiredException(union, field)
case "optional" => new UnionFieldOptionalException(union, field)
}
}
}
class InvalidThriftFilenameException(filename: String, regex: String)
extends ParseWarning("Thrift filename " + filename + " is invalid, did not pass this check: " + regex)
class KeywordException(id: String)
extends ParseWarning(s"Identifier '$id' is invalid: it is a thrift keyword.")
class ScroogeInternalException(msg: String) extends Exception
示例10: IbanValidationException
//设置package包名称以及导入依赖的类
package com.snapswap.ibancom
import scala.util.control.NoStackTrace
trait IbanComException extends NoStackTrace
case class IbanValidationException(messages: Seq[String]) extends IbanComException {
override def getMessage: String = {
messages.mkString(", ")
}
}
case class InvalidRequestException(messages: Seq[String]) extends IbanComException {
override def getMessage: String = {
messages.mkString(", ")
}
}
case class UnexpectedResponseException(message: String) extends IbanComException {
override def getMessage: String = {
message
}
}
示例11: InputActionTest
//设置package包名称以及导入依赖的类
package com.nthportal.shell
package async
import com.nthportal.shell.impl.{StatefulOutputProvider, TestCommand}
import com.nthportal.shell.parsers.WhitespaceDelineatingParser
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import scala.util.control.NoStackTrace
class InputActionTest extends SimpleSpec {
behavior of classOf[InputAction[_]].getSimpleName
it should "execute an execution properly" in {
val os = StatefulOutputProvider()
val shell = Shell(WhitespaceDelineatingParser, os)
val ex = InputAction.execution("not-a-command")
val f = ex.future
f.isCompleted should be(false)
os.writtenTo should be(false)
ex.doAction(shell)
f.isCompleted should be(true)
os.writtenTo should be(true)
}
it should "execute a tab-completion properly" in {
val t = TestCommand()
val shell = Shell(WhitespaceDelineatingParser, StatefulOutputProvider(), t)
val tc = InputAction.tabCompletion(t.name)
val f = tc.future
f.isCompleted should be(false)
tc.doAction(shell)
f.isCompleted should be(true)
Await.result(f, Duration.Zero) should contain(t.name)
}
it should "return a failed Future if the action throws an exception" in {
val shell = Shell(WhitespaceDelineatingParser, StatefulOutputProvider())
val ex = new Exception with NoStackTrace
val action: InputAction[Unit] = _ => throw ex
val f = action.future
action.doAction(shell)
f.isCompleted should be(true)
Await.result(f.failed, Duration.Zero) should be(ex)
}
}
示例12: GoAway
//设置package包名称以及导入依赖的类
package com.twitter.finagle.buoyant.h2
import scala.util.control.NoStackTrace
sealed trait Error
extends Throwable
with NoStackTrace
sealed trait GoAway extends Error
object GoAway {
object EnhanceYourCalm extends GoAway { override def toString = "GoAway.EnhanceYourCalm" }
object InternalError extends GoAway { override def toString = "GoAway.InternalError" }
object NoError extends GoAway { override def toString = "GoAway.NoError" }
object ProtocolError extends GoAway { override def toString = "GoAway.ProtocolError" }
}
sealed trait Reset extends Error
object Reset {
object Cancel extends Reset { override def toString = "Reset.Cancel" }
object Closed extends Reset { override def toString = "Reset.Closed" }
object EnhanceYourCalm extends Reset { override def toString = "Reset.EnhanceYourCalm" }
object InternalError extends Reset { override def toString = "Reset.InternalError" }
object ProtocolError extends Reset { override def toString = "Reset.ProtocolError" }
object NoError extends Reset { override def toString = "Reset.NoError" }
object Refused extends Reset { override def toString = "Reset.Refused" }
}
sealed trait StreamError
extends Throwable
with NoStackTrace {
def cause: Throwable
}
object StreamError {
case class Local(cause: Throwable) extends StreamError {
override def toString = s"StreamError.Local(${cause.toString})"
override def getMessage = s"local: ${cause.getMessage}"
}
case class Remote(cause: Throwable) extends StreamError {
override def toString = s"StreamError.Remote(${cause.toString})"
override def getMessage = s"remote: ${cause.getMessage}"
}
def unapply(e: StreamError): Option[Throwable] = Some(e.cause)
}
示例13: newInterpreter
//设置package包名称以及导入依赖的类
package io.buoyant.interpreter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.twitter.conversions.time._
import com.twitter.finagle._
import com.twitter.finagle.buoyant.{H2, TlsClientConfig}
import com.twitter.finagle.naming.NameInterpreter
import com.twitter.finagle.service.Backoff
import com.twitter.finagle.util.DefaultTimer
import com.twitter.logging.Logger
import io.buoyant.interpreter.mesh.Client
import io.buoyant.namer.{InterpreterConfig, InterpreterInitializer}
import scala.util.control.NoStackTrace
@JsonIgnore
def newInterpreter(params: Stack.Params): NameInterpreter = {
val name = dst match {
case None => throw new IllegalArgumentException("`dst` is a required field") with NoStackTrace
case Some(dst) => Name.Path(dst)
}
val label = MeshInterpreterInitializer.configId
val Retry(baseRetry, maxRetry) = retry.getOrElse(defaultRetry)
val backoffs = Backoff.exponentialJittered(baseRetry.seconds, maxRetry.seconds)
val tlsParams = tls.map(_.params).getOrElse(Stack.Params.empty)
val client = H2.client
.withParams(H2.client.params ++ tlsParams ++ params)
.newService(name, label)
root.getOrElse(DefaultRoot) match {
case [email protected](_) =>
Client(r, client, backoffs, DefaultTimer)
case r =>
val msg = s"io.l5d.mesh: `root` may only contain a single path element (for now): ${r.show}"
throw new IllegalArgumentException(msg) with NoStackTrace
}
}
}
示例14: NoRoutersSpecified
//设置package包名称以及导入依赖的类
package io.buoyant.config
import com.fasterxml.jackson.databind.jsontype.NamedType
import java.net.InetSocketAddress
import scala.util.control.NoStackTrace
trait ConfigError extends NoStackTrace
object NoRoutersSpecified extends ConfigError {
def message = "At least one router must be specified in the configuration."
}
case class ConflictingSubtypes(t0: NamedType, t1: NamedType) extends ConfigError {
def message = s"Conflicting subtypes: $t0, $t1"
}
case class ConflictingLabels(name: String) extends ConfigError {
def message = s"Multiple routers with the label $name"
}
case class ConflictingPorts(
addr0: InetSocketAddress,
addr1: InetSocketAddress
) extends ConfigError {
def message = s"Server conflict on port ${addr0.getPort}"
}
示例15: ConsoleInput
//设置package包名称以及导入依赖的类
package example.akkawschat.cli
import akka.stream.stage.{ OutHandler, GraphStageLogic, GraphStage }
import akka.stream._
import scala.annotation.tailrec
import scala.concurrent.{ Future, ExecutionContext }
import scala.util.control.NoStackTrace
class ConsoleInput(implicit ec: ExecutionContext) extends GraphStage[SourceShape[Char]] {
val out = Outlet[Char]("consoleOut")
val shape: SourceShape[Char] = SourceShape(out)
def createLogic(inheritedAttributes: Attributes): GraphStageLogic =
new GraphStageLogic(shape) {
TTY.noEchoStty()
@volatile var cancelled = false
def getOne(): Unit = {
val callback = getAsyncCallback[Char](push(out, _))
Future {
@tailrec def read(): Unit =
if (cancelled) throw new Exception with NoStackTrace
else if (System.in.available() > 0)
callback.invoke(System.in.read().toChar)
else {
Thread.sleep(10)
read()
}
read()
}
}
setHandler(out, new OutHandler {
def onPull(): Unit = getOne()
override def onDownstreamFinish(): Unit = {
cancelled = true
super.onDownstreamFinish()
}
})
override def postStop(): Unit =
TTY.saneStty()
}
}