Skip to content

#[from] and #[source] Box<dyn std::error::Error> does not work #23

@parasyte

Description

@parasyte

Test case:

use onlyerror::Error;

#[derive(Debug, Error)]
enum Error {
    /// foo
    Foo(#[from] Box<dyn std::error::Error>),
}

The generated code looks like this:

impl ::std::error::Error for Error {
    fn source(&self) -> Option<&(dyn ::std::error::Error + 'static)> {
        match self {
            Self::Foo(field) => Some(field),
            _ => None,
        }
    }
}

impl ::std::convert::From<Box<dynstd::error::Error>> for Error {
    fn from(value: Box<dynstd::error::Error>) -> Self {
        Self::Foo(value)
    }
}

Which fails to build:

error[E0433]: cannot find module or crate `dynstd` in this scope
 --> src/main.rs:3:17
  |
3 | #[derive(Debug, Error)]
  |                 ^^^^^ use of unresolved module or unlinked crate `dynstd`
  |
  = help: if you wanted to use a crate named `dynstd`, use `cargo add dynstd` to add it to your `Cargo.toml`
  = note: this error originates in the derive macro `Error` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider importing this module
  |
1 + use std::error;
  |

error[E0277]: the size for values of type `(dyn std::error::Error + 'static)` cannot be known at compilation time
    --> src/main.rs:3:17
     |
   3 | #[derive(Debug, Error)]
     |                 ^^^^^ doesn't have a size known at compile-time
     |
     = help: the trait `Sized` is not implemented for `(dyn std::error::Error + 'static)`
help: the trait `std::error::Error` is implemented for `Box<E>`
    --> /Users/parasyte/.rustup/toolchains/nightly-aarch64-apple-darwin/lib/rustlib/src/rust/library/alloc/src/boxed.rs:2385:1
     |
2385 | impl<E: Error> Error for Box<E> {
     | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     = note: required for `Box<(dyn std::error::Error + 'static)>` to implement `std::error::Error`
     = note: required for the cast from `&Box<(dyn std::error::Error + 'static)>` to `&dyn std::error::Error`
     = note: this error originates in the derive macro `Error` (in Nightly builds, run with -Z macro-backtrace for more info)

The generated Display impl is missing a space after the dyn token, and the Error impl needs to deref the box: Some(&**field) or Some(field.as_ref()).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions