core: impl Value for dyn Error + Send/Sync (#2066)

## Motivation

`Value` was already implemented for `dyn Error + 'static`, but rust
doesn't silently coerce trait objects. This means that passing an error
of type `dyn Error + Send + Sync + 'static` would not work. This is
related to #1308.

## Solution

Add impls for `dyn Error + …` variants for `Send`, `Sync`, and `Send +
Sync`. These extra impls just delegate to the existing `dyn Error +
'static` impl.

Also update one of the examples to use `dyn Error + Send + Sync` to
demonstrate that this works.

Refs: #1308
This commit is contained in:
Lily Ballard 2022-04-11 15:42:00 -07:00 committed by Eliza Weisman
parent fc694a5bcc
commit 50a726b647
No known key found for this signature in database
GPG Key ID: F9C1A595C3814436
2 changed files with 34 additions and 1 deletions

View File

@ -7,7 +7,7 @@ use tracing::{debug, error, info, span, trace, warn, Level};
// every time the instrumented function is called. The span is named after the
// the function or method. Paramaters passed to the function are recorded as fields.
#[tracing::instrument]
pub fn shave(yak: usize) -> Result<(), Box<dyn Error + 'static>> {
pub fn shave(yak: usize) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
// this creates an event at the TRACE log level with two fields:
// - `excitement`, with the key "excitement" and the value "yay!"
// - `message`, with the key "message" and the value "hello! I'm gonna shave a yak."

View File

@ -523,6 +523,39 @@ impl Value for dyn std::error::Error + 'static {
}
}
#[cfg(feature = "std")]
impl crate::sealed::Sealed for dyn std::error::Error + Send + 'static {}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Value for dyn std::error::Error + Send + 'static {
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
(self as &dyn std::error::Error).record(key, visitor)
}
}
#[cfg(feature = "std")]
impl crate::sealed::Sealed for dyn std::error::Error + Sync + 'static {}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Value for dyn std::error::Error + Sync + 'static {
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
(self as &dyn std::error::Error).record(key, visitor)
}
}
#[cfg(feature = "std")]
impl crate::sealed::Sealed for dyn std::error::Error + Send + Sync + 'static {}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Value for dyn std::error::Error + Send + Sync + 'static {
fn record(&self, key: &Field, visitor: &mut dyn Visit) {
(self as &dyn std::error::Error).record(key, visitor)
}
}
impl<'a, T: ?Sized> crate::sealed::Sealed for &'a T where T: Value + crate::sealed::Sealed + 'a {}
impl<'a, T: ?Sized> Value for &'a T