{"record":{"id":"df9f99bfb1458b1e","repo":"tokio-rs/tokio","slug":"can-t-get-a-task-id-when-not-inside-a-task","errorCode":null,"errorMessage":"Can't get a task id when not inside a task","messagePattern":"Can't get a task id when not inside a task","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tokio/src/runtime/task/id.rs","lineNumber":46,"sourceCode":"/// [`AbortHandle`]: crate::task::AbortHandle\n/// [`JoinSet`]: crate::task::JoinSet\n#[cfg_attr(docsrs, doc(cfg(all(feature = \"rt\"))))]\n#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, PartialOrd, Ord)]\npub struct Id(pub(crate) NonZeroU64);\n\n/// Returns the [`Id`] of the currently running task.\n///\n/// # Panics\n///\n/// This function panics if called from outside a task. Please note that calls\n/// to `block_on` do not have task IDs, so the method will panic if called from\n/// within a call to `block_on`. For a version of this function that doesn't\n/// panic, see [`task::try_id()`](crate::runtime::task::try_id()).\n///\n/// [task ID]: crate::task::Id\n#[track_caller]\npub fn id() -> Id {\n    context::current_task_id().expect(\"Can't get a task id when not inside a task\")\n}\n\n/// Returns the [`Id`] of the currently running task, or `None` if called outside\n/// of a task.\n///\n/// This function is similar to  [`task::id()`](crate::runtime::task::id()), except\n/// that it returns `None` rather than panicking if called outside of a task\n/// context.\n///\n/// [task ID]: crate::task::Id\n#[track_caller]\npub fn try_id() -> Option<Id> {\n    context::current_task_id()\n}\n\nimpl fmt::Display for Id {\n    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n        self.0.fmt(f)","sourceCodeStart":28,"sourceCodeEnd":64,"githubUrl":"https://github.com/tokio-rs/tokio/blob/625954f365727668cb02d04172b34f1149637728/tokio/src/runtime/task/id.rs#L28-L64","documentation":"task::id() calls context::current_task_id().expect('Can\\'t get a task id when not inside a task'). It panics when invoked outside a spawned task — including from block_on bodies, which do not carry a task ID. The doc note explicitly warns block_on has no task ID.","triggerScenarios":"Calling tokio::task::id() from the top-level future inside runtime.block_on, from a non-runtime thread, or from a synchronous context.","commonSituations":"Using task::id() inside the async fn passed to #[tokio::main] (the main future is block_on, not a task); calling from a thread that did not enter a task context; logging/metrics code that assumes it always runs in a task.","solutions":["Use tokio::task::try_id() which returns Option<Id> instead of panicking.","Call task::id() only inside futures spawned via tokio::spawn / spawn_local.","If you need an ID in the block_on body, spawn the work as a task and await its JoinHandle.","Guard instrumentation code with try_id() and fall back to a synthetic ID."],"exampleFix":"// before\nruntime.block_on(async {\n    let id = tokio::task::id(); // panics: not inside a task\n});\n// after\nruntime.block_on(async {\n    let id = tokio::task::try_id(); // Option<Id>\n});\n// or\nruntime.block_on(async {\n    let h = tokio::spawn(async { tokio::task::id() });\n    let id = h.await.unwrap();\n});","handlingStrategy":"type-guard","validationCode":"// Use the non-panicking variant when context is uncertain:\nlet id = tokio::task::try_id(); // Option<Id>","typeGuard":"fn current_id_or_none() -> Option<tokio::task::Id> {\n    tokio::task::try_id()\n}","tryCatchPattern":"// For instrumentation that may run outside a task:\nlet label = tokio::task::try_id()\n    .map(|id| id.to_string())\n    .unwrap_or_else(|| \"no-task\".to_string());","preventionTips":["Default to try_id() in library code.","Only call id() inside futures spawned via tokio::spawn.","Wrap block_on body work in tokio::spawn if you need a task ID."],"tags":["task","task-id","panic","context","block-on"],"backgroundTag":null,"analyzedSha":"625954f365727668cb02d04172b34f1149637728","analyzedAt":"2026-08-11T17:46:45.378Z","contentChangedAt":"2026-08-11T17:46:45.378Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}