Skip to content

Commit ecfcd2a

Browse files
committed
Auto merge of #26416 - retep998:error-debug, r=sfackler
Fixes #26408 Example output when using `Result::unwrap`: ``` thread '<main>' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "The system cannot find the file specified.\r\n" } }', src/libcore\result.rs:731 ``` This could technically be considered a breaking change for any code that depends on the format of the `Debug` output for `io::Error` but I sincerely hope nobody wrote code like that.
2 parents 7d6e790 + c8aec53 commit ecfcd2a

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

src/libstd/io/error.rs

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ pub struct Error {
3737
repr: Repr,
3838
}
3939

40-
#[derive(Debug)]
4140
enum Repr {
4241
Os(i32),
4342
Custom(Box<Custom>),
@@ -240,6 +239,17 @@ impl Error {
240239
}
241240
}
242241

242+
impl fmt::Debug for Repr {
243+
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
244+
match self {
245+
&Repr::Os(ref code) =>
246+
fmt.debug_struct("Os").field("code", code)
247+
.field("message", &sys::os::error_string(*code)).finish(),
248+
&Repr::Custom(ref c) => fmt.debug_tuple("Custom").field(c).finish(),
249+
}
250+
}
251+
}
252+
243253
#[stable(feature = "rust1", since = "1.0.0")]
244254
impl fmt::Display for Error {
245255
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
@@ -282,6 +292,16 @@ mod test {
282292
use error;
283293
use error::Error as error_Error;
284294
use fmt;
295+
use sys::os::error_string;
296+
297+
#[test]
298+
fn test_debug_error() {
299+
let code = 6;
300+
let msg = error_string(code);
301+
let err = Error { repr: super::Repr::Os(code) };
302+
let expected = format!("Error {{ repr: Os {{ code: {:?}, message: {:?} }} }}", code, msg);
303+
assert_eq!(format!("{:?}", err), expected);
304+
}
285305

286306
#[test]
287307
fn test_downcasting() {

0 commit comments

Comments
 (0)