Skip to content

Commit

Permalink
runtime: add Handle::try_current (#2118)
Browse files Browse the repository at this point in the history
* runtime: add Handle::try_current

Makes it possible to get a Handle only if a Runtime has been started, without panicing if that isn't the case

* Use an error instead
  • Loading branch information
tomaka authored and LucioFranco committed Jan 20, 2020
1 parent 7eb8d44 commit 1475448
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
27 changes: 27 additions & 0 deletions tokio/src/runtime/handle.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::runtime::{blocking, context, io, time, Spawner};
use std::{error, fmt};

cfg_rt_core! {
use crate::task::JoinHandle;
Expand Down Expand Up @@ -61,6 +62,15 @@ impl Handle {
pub fn current() -> Self {
context::current().expect("not currently running on the Tokio runtime.")
}

/// Returns a Handle view over the currently running Runtime
///
/// Returns an error if no Runtime has been started
///
/// Contrary to `current`, this never panics
pub fn try_current() -> Result<Self, TryCurrentError> {
context::current().ok_or(TryCurrentError(()))
}
}

cfg_rt_core! {
Expand Down Expand Up @@ -105,3 +115,20 @@ cfg_rt_core! {
}
}
}

/// Error returned by `try_current` when no Runtime has been started
pub struct TryCurrentError(());

impl fmt::Debug for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TryCurrentError").finish()
}
}

impl fmt::Display for TryCurrentError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("no tokio Runtime has been initialized")
}
}

impl error::Error for TryCurrentError {}
2 changes: 1 addition & 1 deletion tokio/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ pub(crate) mod enter;
use self::enter::enter;

mod handle;
pub use self::handle::Handle;
pub use self::handle::{Handle, TryCurrentError};

mod io;

Expand Down

0 comments on commit 1475448

Please sign in to comment.