Cannot attach PoisonError to thiserror variant

In my code I want to use thiserror + anyhow and I want to create error variant from PoisonError, but my code not compiles and return an error:

error[E0599]: no method named `map_err` found for struct `tokio::sync::MutexGuard<'_, Option<String>>` in the current scope
  --> src/main.rs:25:10
   |
25 |         .map_err(|source| MutexError::LockAcquired { source })?;
   |          ^^^^^^^ help: there is a method with a similar name: `map_or`

this is my code:

use std::sync::Arc;
use thiserror::Error;
use tokio::sync::{Mutex, mpsc};
use anyhow::{Context, Result};

#[derive(Error, Debug)]
pub enum MutexError<T> {
    #[error("lock is acquired")]
    LockAcquired { source: std::sync::PoisonError<T> },
}

struct Test {
    item: Arc<Mutex<Option<String>>>,
}

#[tokio::main]
async fn main() -> Result<()> {
    let test = Test {
        item: Arc::new(Mutex::new(None)),
    };
    
    let x = test.item
        .lock()
        .await
        .map_err(|source| MutexError::LockAcquired { source })?;
        
    Ok(())
}

This is sandbox to reproduce.

Could somebody explain how to fix this issue and correctly attach custom error to mutex ?

tokio's Mutex::lock doesn't return a Result, so there's no error to map.

Note that in contrast to std::sync::Mutex, this implementation does not poison the mutex when a thread holding the MutexGuard panics. In such a case, the mutex will be unlocked. If the panic is caught, this might leave the data protected by the mutex in an inconsistent state.

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.