简体   繁体   中英

How to do: Try {block of code} for X duration and catch {Exceptions, such as Timeout}?

Alright so the title is a little obscure since I was unsure how to word it, but essentially I am trying to do a try-catch statement that will timeout... Here's some pseudo-code that may help describe what I'm trying to do:

try (10 seconds) {
  *make some connection and do some things*
} catch {
  case ex1: TimeoutException => *do something*
  case ex2: Exception => *do something else*
}

Currently there is a bug in the hardware I'm working with where the request for a connection never gets a response back, so it just sits there and doesn't catch any exceptions. Since it's only a bug (that should be temporary), I don't want to manipulate the architecture of the application (specifically I do not want to create a new actor just to account for something small) and it would be very ideal if I could implement this pseudo-code within the scope of the class.

So essentially my question is how do I implement the pseudo-code above within the scope of the class it's in?

Let me know if anything is unclear! Thank you!

Try:

import scala.concurrent._
import ExecutionContext.Implicits.global

val f = future {
    // make some connection and do some things
}
try {
    Await.result(f, 10 seconds);
} catch {
    case e: TimeoutException => // do something
    case _ => // do something else
}

More info: Futures and Promises

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM