Rollup merge of #47120 - clarcharr:io_error_debug, r=dtolnay

Better Debug impl for io::Error.

This PR includes the below changes:

1. The former impl wrapped the entire thing in `Error { repr: ... }` which was unhelpful; this has been removed.
2. The `Os` variant of `io::Error` included the code and message, but not the kind; this has been fixed.
3. The `Custom` variant of `io::Error` included a `Custom(Custom { ... })`, which is now just `Custom { ... }`.

Example of previous impl:

```rust
Error {
    repr: Custom(
        Custom {
            kind: InvalidData,
            error: Error {
                repr: Os {
                    code: 2,
                    message: "no such file or directory"
                }
            }
        }
    )
}
```

Example of new impl:

```rust
Custom {
    kind: InvalidData,
    error: Os {
        code: 2,
        kind: NotFound,
        message: "no such file or directory"
    }
}
```
This commit is contained in:
kennytm 2018-01-15 16:55:26 +08:00
commit 06112abd5f
No known key found for this signature in database
GPG key ID: FEF6C8051D0E013C

View file

@ -62,12 +62,18 @@
/// [`Write`]: ../io/trait.Write.html
/// [`Seek`]: ../io/trait.Seek.html
/// [`ErrorKind`]: enum.ErrorKind.html
#[derive(Debug)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Error {
repr: Repr,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.repr, f)
}
}
enum Repr {
Os(i32),
Simple(ErrorKind),
@ -511,10 +517,12 @@ pub fn kind(&self) -> ErrorKind {
impl fmt::Debug for Repr {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
match *self {
Repr::Os(ref code) =>
fmt.debug_struct("Os").field("code", code)
.field("message", &sys::os::error_string(*code)).finish(),
Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
Repr::Os(code) =>
fmt.debug_struct("Os")
.field("code", &code)
.field("kind", &sys::decode_error_kind(code))
.field("message", &sys::os::error_string(code)).finish(),
Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
}
}
@ -559,17 +567,36 @@ fn _is_sync_send<T: Sync+Send>() {}
#[cfg(test)]
mod test {
use super::{Error, ErrorKind};
use super::{Error, ErrorKind, Repr, Custom};
use error;
use fmt;
use sys::os::error_string;
use sys::decode_error_kind;
#[test]
fn test_debug_error() {
let code = 6;
let msg = error_string(code);
let err = Error { repr: super::Repr::Os(code) };
let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
let kind = decode_error_kind(code);
let err = Error {
repr: Repr::Custom(box Custom {
kind: ErrorKind::InvalidInput,
error: box Error {
repr: super::Repr::Os(code)
},
})
};
let expected = format!(
"Custom {{ \
kind: InvalidInput, \
error: Os {{ \
code: {:?}, \
kind: {:?}, \
message: {:?} \
}} \
}}",
code, kind, msg
);
assert_eq!(format!("{:?}", err), expected);
}