Implementing Send in thiserror enum

I have a very basic enum Error that is returned in a Result of an async function that needs to implement Send in a tokio executor application (Tauri):

use std::convert::{TryFrom, TryInto};
use surrealdb::sql::{Array, Object, Value};

#[derive(thiserror::Error, Debug)]
pub enum Error {
  #[error("Fail to get Ctx")]
  CtxFail,

  #[error("Value not of type '{0}'")]
  XValueNotOfType(&'static str),

  #[error("Property '{0}' not found")]
  XPropertyNotFound(String),

  #[error("Fail to create. Cause: {0}")]
  StoreFailToCreate(String),

  #[error(transparent)]
  Surreal(#[from] surrealdb::Error),

  #[error(transparent)]
  IO(#[from] std::io::Error),
}


pub type Result<T> = core::result::Result<T, Error>;

How do I add + Send to type Result if it is an enum?

Whether an enum is Send is determined by its fields. You cannot put + Send to change that.

That said, looking over your fields, it seems like it should be Send without you having to do anything. What makes you conclude it isn't?

1 Like

ugh... you're right. I only got that error after I added a function that returned that thiserror Result, but I now realize the issue is that Result is only returned if some other async function returns successfully, and hence that other code must implement Send also since it may pass (send) context between threads from the two async functions? :stuck_out_tongue:

For instance:

match code_that_didnt_implement_send_sync().await {
  case Ok(res) => code_that_did().await?
  case ..
}

The solution was for the first function to return Result<.., Box<dyn std::Error + Send + Sync>> per: Convert Box<dyn Error> to Box<dyn Error + Send> - #3 by david_am

But I have no idea why Sync is also necessary =)... well, I guess it's just an implementation detail because you guys always implement Sync when you implement Send

For reference - this is probably because you can use question mark to convert T: Error to Box<dyn Error> or Box<dyn Error + Send + Sync>, but not to Box<dyn Error + Send>, since there isn't From implementation for the latter.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.