Sphere
Log in Join
☆ 14

Box<dyn Error> not Send when using thread::spawn

I have a function returning Result<(), Box<dyn Error>> and I call it inside std::thread::spawn. Compiler says:

error[E0277]: dyn Error cannot be sent between threads safely
--> src/worker.rs:14:21
|
14 | thread::spawn(move || -> Result<(), Box<dyn Error>> { ... });
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ closure may outlive the current function

How do people usually return errors from spawned threads? Do I need Box<dyn Error + Send + Sync> everywhere?

⚑ Report

4 replies

☆ 0
8 808 ·2026-10-11#1

Yes, that's the common fix: Box<dyn Error + Send + Sync>. It's verbose so people define type BoxError = Box<dyn Error + Send + Sync>; and use that alias. anyhow::Error and eyre::Report are already Send + Sync and are the popular choices if you're open to a dependency.

⚑ Report
☆ 0
N null ·2026-10-20#2

I'd rather not pull in anyhow for this one spot. If I use the alias, do all my ? conversions still work? Most of my errors are io::Error and serde_json::Error. I checked the other error types in this crate and none of them hold an Rc, so the Send + Sync bound should be fine everywhere. I'll make the change and run the full build to be sure.

⚑ Report
☆ 0
K kp ·2026-10-30#3

Both of those are Send + Sync, so ? will convert them into the boxed trait object fine. You only hit trouble if one of your error types holds an Rc or something else non-Send. Then you'd have to either change that type or stop returning it across the thread boundary.

⚑ Report
☆ 0
R route ·2026-10-31#4

Type alias with + Send + Sync did it, no new dependency. All my ? operators kept working. I'll probably reach for anyhow on the next bigger project, but for this it was overkill. Curious whether that holds up for you.

⚑ Report
Log in to reply.