1 //! Interfaces for working with Errors.
3 //! # Error Handling In Rust
5 //! The Rust language provides two complementary systems for constructing /
6 //! representing, reporting, propagating, reacting to, and discarding errors.
7 //! These responsibilities are collectively known as "error handling." The
8 //! components of the first system, the panic runtime and interfaces, are most
9 //! commonly used to represent bugs that have been detected in your program. The
10 //! components of the second system, `Result`, the error traits, and user
11 //! defined types, are used to represent anticipated runtime failure modes of
14 //! ## The Panic Interfaces
16 //! The following are the primary interfaces of the panic system and the
17 //! responsibilities they cover:
19 //! * [`panic!`] and [`panic_any`] (Constructing, Propagated automatically)
20 //! * [`PanicInfo`] (Reporting)
21 //! * [`set_hook`], [`take_hook`], and [`#[panic_handler]`][panic-handler] (Reporting)
22 //! * [`catch_unwind`] and [`resume_unwind`] (Discarding, Propagating)
24 //! The following are the primary interfaces of the error system and the
25 //! responsibilities they cover:
27 //! * [`Result`] (Propagating, Reacting)
28 //! * The [`Error`] trait (Reporting)
29 //! * User defined types (Constructing / Representing)
30 //! * [`match`] and [`downcast`] (Reacting)
31 //! * The question mark operator ([`?`]) (Propagating)
32 //! * The partially stable [`Try`] traits (Propagating, Constructing)
33 //! * [`Termination`] (Reporting)
35 //! ## Converting Errors into Panics
37 //! The panic and error systems are not entirely distinct. Often times errors
38 //! that are anticipated runtime failures in an API might instead represent bugs
39 //! to a caller. For these situations the standard library provides APIs for
40 //! constructing panics with an `Error` as it's source.
42 //! * [`Result::unwrap`]
43 //! * [`Result::expect`]
45 //! These functions are equivalent, they either return the inner value if the
46 //! `Result` is `Ok` or panic if the `Result` is `Err` printing the inner error
47 //! as the source. The only difference between them is that with `expect` you
48 //! provide a panic error message to be printed alongside the source, whereas
49 //! `unwrap` has a default message indicating only that you unwraped an `Err`.
51 //! Of the two, `expect` is generally preferred since its `msg` field allows you
52 //! to convey your intent and assumptions which makes tracking down the source
53 //! of a panic easier. `unwrap` on the other hand can still be a good fit in
54 //! situations where you can trivially show that a piece of code will never
55 //! panic, such as `"127.0.0.1".parse::<std::net::IpAddr>().unwrap()` or early
58 //! # Common Message Styles
60 //! There are two common styles for how people word `expect` messages. Using
61 //! the message to present information to users encountering a panic
62 //! ("expect as error message") or using the message to present information
63 //! to developers debugging the panic ("expect as precondition").
65 //! In the former case the expect message is used to describe the error that
66 //! has occurred which is considered a bug. Consider the following example:
69 //! // Read environment variable, panic if it is not present
70 //! let path = std::env::var("IMPORTANT_PATH").unwrap();
73 //! In the "expect as error message" style we would use expect to describe
74 //! that the environment variable was not set when it should have been:
77 //! let path = std::env::var("IMPORTANT_PATH")
78 //! .expect("env variable `IMPORTANT_PATH` is not set");
81 //! In the "expect as precondition" style, we would instead describe the
82 //! reason we _expect_ the `Result` should be `Ok`. With this style we would
86 //! let path = std::env::var("IMPORTANT_PATH")
87 //! .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`");
90 //! The "expect as error message" style does not work as well with the
91 //! default output of the std panic hooks, and often ends up repeating
92 //! information that is already communicated by the source error being
96 //! thread 'main' panicked at 'env variable `IMPORTANT_PATH` is not set: NotPresent', src/main.rs:4:6
99 //! In this example we end up mentioning that an env variable is not set,
100 //! followed by our source message that says the env is not present, the
101 //! only additional information we're communicating is the name of the
102 //! environment variable being checked.
104 //! The "expect as precondition" style instead focuses on source code
105 //! readability, making it easier to understand what must have gone wrong in
106 //! situations where panics are being used to represent bugs exclusively.
107 //! Also, by framing our expect in terms of what "SHOULD" have happened to
108 //! prevent the source error, we end up introducing new information that is
109 //! independent from our source error.
112 //! thread 'main' panicked at 'env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`: NotPresent', src/main.rs:4:6
115 //! In this example we are communicating not only the name of the
116 //! environment variable that should have been set, but also an explanation
117 //! for why it should have been set, and we let the source error display as
118 //! a clear contradiction to our expectation.
120 //! **Hint**: If you're having trouble remembering how to phrase
121 //! expect-as-precondition style error messages remember to focus on the word
122 //! "should" as in "env variable should be set by blah" or "the given binary
123 //! should be available and executable by the current user".
125 //! [`panic_any`]: crate::panic::panic_any
126 //! [`PanicInfo`]: crate::panic::PanicInfo
127 //! [`catch_unwind`]: crate::panic::catch_unwind
128 //! [`resume_unwind`]: crate::panic::resume_unwind
129 //! [`downcast`]: crate::error::Error
130 //! [`Termination`]: crate::process::Termination
131 //! [`Try`]: crate::ops::Try
132 //! [panic hook]: crate::panic::set_hook
133 //! [`set_hook`]: crate::panic::set_hook
134 //! [`take_hook`]: crate::panic::take_hook
135 //! [panic-handler]: <https://doc.rust-lang.org/nomicon/panic-handler.html>
136 //! [`match`]: ../../std/keyword.match.html
137 //! [`?`]: ../../std/result/index.html#the-question-mark-operator-
139 #![stable(feature = "rust1", since = "1.0.0")]
141 // A note about crates and the facade:
143 // Originally, the `Error` trait was defined in libcore, and the impls
144 // were scattered about. However, coherence objected to this
145 // arrangement, because to create the blanket impls for `Box` required
146 // knowing that `&str: !Error`, and we have no means to deal with that
147 // sort of conflict just now. Therefore, for the time being, we have
148 // moved the `Error` trait into libstd. As we evolve a sol'n to the
149 // coherence challenge (e.g., specialization, neg impls, etc) we can
150 // reconsider what crate these items belong in.
156 use core::convert::Infallible;
158 use crate::alloc::{AllocError, LayoutError};
159 use crate::any::TypeId;
160 use crate::backtrace::Backtrace;
161 use crate::borrow::Cow;
164 use crate::fmt::{self, Debug, Display, Write};
166 use crate::mem::transmute;
170 use crate::sync::Arc;
173 /// `Error` is a trait representing the basic expectations for error values,
174 /// i.e., values of type `E` in [`Result<T, E>`].
176 /// Errors must describe themselves through the [`Display`] and [`Debug`]
177 /// traits. Error messages are typically concise lowercase sentences without
178 /// trailing punctuation:
181 /// let err = "NaN".parse::<u32>().unwrap_err();
182 /// assert_eq!(err.to_string(), "invalid digit found in string");
185 /// Errors may provide cause chain information. [`Error::source()`] is generally
186 /// used when errors cross "abstraction boundaries". If one module must report
187 /// an error that is caused by an error from a lower-level module, it can allow
188 /// accessing that error via [`Error::source()`]. This makes it possible for the
189 /// high-level module to provide its own errors while also revealing some of the
190 /// implementation for debugging via `source` chains.
191 #[stable(feature = "rust1", since = "1.0.0")]
192 #[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
193 pub trait Error: Debug + Display {
194 /// The lower-level source of this error, if any.
199 /// use std::error::Error;
203 /// struct SuperError {
204 /// source: SuperErrorSideKick,
207 /// impl fmt::Display for SuperError {
208 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 /// write!(f, "SuperError is here!")
213 /// impl Error for SuperError {
214 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
215 /// Some(&self.source)
220 /// struct SuperErrorSideKick;
222 /// impl fmt::Display for SuperErrorSideKick {
223 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 /// write!(f, "SuperErrorSideKick is here!")
228 /// impl Error for SuperErrorSideKick {}
230 /// fn get_super_error() -> Result<(), SuperError> {
231 /// Err(SuperError { source: SuperErrorSideKick })
235 /// match get_super_error() {
237 /// println!("Error: {e}");
238 /// println!("Caused by: {}", e.source().unwrap());
240 /// _ => println!("No error"),
244 #[stable(feature = "error_source", since = "1.30.0")]
245 fn source(&self) -> Option<&(dyn Error + 'static)> {
249 /// Gets the `TypeId` of `self`.
252 feature = "error_type_id",
253 reason = "this is memory-unsafe to override in user code",
256 fn type_id(&self, _: private::Internal) -> TypeId
263 /// Returns a stack backtrace, if available, of where this error occurred.
265 /// This function allows inspecting the location, in code, of where an error
266 /// happened. The returned `Backtrace` contains information about the stack
267 /// trace of the OS thread of execution of where the error originated from.
269 /// Note that not all errors contain a `Backtrace`. Also note that a
270 /// `Backtrace` may actually be empty. For more information consult the
271 /// `Backtrace` type itself.
272 #[unstable(feature = "backtrace", issue = "53487")]
273 fn backtrace(&self) -> Option<&Backtrace> {
278 /// if let Err(e) = "xc".parse::<u32>() {
279 /// // Print `e` itself, no need for description().
280 /// eprintln!("Error: {e}");
283 #[stable(feature = "rust1", since = "1.0.0")]
284 #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")]
285 fn description(&self) -> &str {
286 "description() is deprecated; use Display"
289 #[stable(feature = "rust1", since = "1.0.0")]
292 note = "replaced by Error::source, which can support downcasting"
294 #[allow(missing_docs)]
295 fn cause(&self) -> Option<&dyn Error> {
301 // This is a hack to prevent `type_id` from being overridden by `Error`
302 // implementations, since that can enable unsound downcasting.
303 #[unstable(feature = "error_type_id", issue = "60784")]
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
310 /// Converts a type of [`Error`] into a box of dyn [`Error`].
315 /// use std::error::Error;
322 /// impl fmt::Display for AnError {
323 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 /// write!(f, "An error")
328 /// impl Error for AnError {}
330 /// let an_error = AnError;
331 /// assert!(0 == mem::size_of_val(&an_error));
332 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
333 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
335 fn from(err: E) -> Box<dyn Error + 'a> {
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
342 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
343 /// dyn [`Error`] + [`Send`] + [`Sync`].
348 /// use std::error::Error;
355 /// impl fmt::Display for AnError {
356 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
357 /// write!(f, "An error")
361 /// impl Error for AnError {}
363 /// unsafe impl Send for AnError {}
365 /// unsafe impl Sync for AnError {}
367 /// let an_error = AnError;
368 /// assert!(0 == mem::size_of_val(&an_error));
369 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
371 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
373 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl From<String> for Box<dyn Error + Send + Sync> {
380 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
385 /// use std::error::Error;
388 /// let a_string_error = "a string error".to_string();
389 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
391 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
394 fn from(err: String) -> Box<dyn Error + Send + Sync> {
395 struct StringError(String);
397 impl Error for StringError {
399 fn description(&self) -> &str {
404 impl Display for StringError {
405 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406 Display::fmt(&self.0, f)
410 // Purposefully skip printing "StringError(..)"
411 impl Debug for StringError {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 Debug::fmt(&self.0, f)
417 Box::new(StringError(err))
421 #[stable(feature = "string_box_error", since = "1.6.0")]
422 impl From<String> for Box<dyn Error> {
423 /// Converts a [`String`] into a box of dyn [`Error`].
428 /// use std::error::Error;
431 /// let a_string_error = "a string error".to_string();
432 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
433 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
435 fn from(str_err: String) -> Box<dyn Error> {
436 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
437 let err2: Box<dyn Error> = err1;
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
444 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
446 /// [`str`]: prim@str
451 /// use std::error::Error;
454 /// let a_str_error = "a str error";
455 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
457 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
460 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
461 From::from(String::from(err))
465 #[stable(feature = "string_box_error", since = "1.6.0")]
466 impl From<&str> for Box<dyn Error> {
467 /// Converts a [`str`] into a box of dyn [`Error`].
469 /// [`str`]: prim@str
474 /// use std::error::Error;
477 /// let a_str_error = "a str error";
478 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
479 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
481 fn from(err: &str) -> Box<dyn Error> {
482 From::from(String::from(err))
486 #[stable(feature = "cow_box_error", since = "1.22.0")]
487 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
488 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
493 /// use std::error::Error;
495 /// use std::borrow::Cow;
497 /// let a_cow_str_error = Cow::from("a str error");
498 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
500 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
502 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
503 From::from(String::from(err))
507 #[stable(feature = "cow_box_error", since = "1.22.0")]
508 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
509 /// Converts a [`Cow`] into a box of dyn [`Error`].
514 /// use std::error::Error;
516 /// use std::borrow::Cow;
518 /// let a_cow_str_error = Cow::from("a str error");
519 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
520 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
522 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
523 From::from(String::from(err))
527 #[unstable(feature = "never_type", issue = "35121")]
531 feature = "allocator_api",
532 reason = "the precise API and guarantees it provides may be tweaked.",
535 impl Error for AllocError {}
537 #[stable(feature = "alloc_layout", since = "1.28.0")]
538 impl Error for LayoutError {}
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl Error for str::ParseBoolError {
543 fn description(&self) -> &str {
544 "failed to parse bool"
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl Error for str::Utf8Error {
551 fn description(&self) -> &str {
552 "invalid utf-8: corrupt contents"
556 #[stable(feature = "rust1", since = "1.0.0")]
557 impl Error for num::ParseIntError {
559 fn description(&self) -> &str {
564 #[stable(feature = "try_from", since = "1.34.0")]
565 impl Error for num::TryFromIntError {
567 fn description(&self) -> &str {
572 #[stable(feature = "try_from", since = "1.34.0")]
573 impl Error for array::TryFromSliceError {
575 fn description(&self) -> &str {
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl Error for num::ParseFloatError {
583 fn description(&self) -> &str {
588 #[stable(feature = "rust1", since = "1.0.0")]
589 impl Error for string::FromUtf8Error {
591 fn description(&self) -> &str {
596 #[stable(feature = "rust1", since = "1.0.0")]
597 impl Error for string::FromUtf16Error {
599 fn description(&self) -> &str {
604 #[stable(feature = "str_parse_error2", since = "1.8.0")]
605 impl Error for Infallible {
606 fn description(&self) -> &str {
611 #[stable(feature = "decode_utf16", since = "1.9.0")]
612 impl Error for char::DecodeUtf16Error {
614 fn description(&self) -> &str {
615 "unpaired surrogate found"
619 #[stable(feature = "u8_from_char", since = "1.59.0")]
620 impl Error for char::TryFromCharError {}
622 #[unstable(feature = "map_try_insert", issue = "82766")]
623 impl<'a, K: Debug + Ord, V: Debug> Error
624 for crate::collections::btree_map::OccupiedError<'a, K, V>
627 fn description(&self) -> &str {
632 #[unstable(feature = "map_try_insert", issue = "82766")]
633 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
635 fn description(&self) -> &str {
640 #[stable(feature = "box_error", since = "1.8.0")]
641 impl<T: Error> Error for Box<T> {
642 #[allow(deprecated, deprecated_in_future)]
643 fn description(&self) -> &str {
644 Error::description(&**self)
648 fn cause(&self) -> Option<&dyn Error> {
649 Error::cause(&**self)
652 fn source(&self) -> Option<&(dyn Error + 'static)> {
653 Error::source(&**self)
657 #[unstable(feature = "thin_box", issue = "92791")]
658 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
659 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
660 use core::ops::Deref;
661 self.deref().source()
665 #[stable(feature = "error_by_ref", since = "1.51.0")]
666 impl<'a, T: Error + ?Sized> Error for &'a T {
667 #[allow(deprecated, deprecated_in_future)]
668 fn description(&self) -> &str {
669 Error::description(&**self)
673 fn cause(&self) -> Option<&dyn Error> {
674 Error::cause(&**self)
677 fn source(&self) -> Option<&(dyn Error + 'static)> {
678 Error::source(&**self)
681 fn backtrace(&self) -> Option<&Backtrace> {
682 Error::backtrace(&**self)
686 #[stable(feature = "arc_error", since = "1.52.0")]
687 impl<T: Error + ?Sized> Error for Arc<T> {
688 #[allow(deprecated, deprecated_in_future)]
689 fn description(&self) -> &str {
690 Error::description(&**self)
694 fn cause(&self) -> Option<&dyn Error> {
695 Error::cause(&**self)
698 fn source(&self) -> Option<&(dyn Error + 'static)> {
699 Error::source(&**self)
702 fn backtrace(&self) -> Option<&Backtrace> {
703 Error::backtrace(&**self)
707 #[stable(feature = "fmt_error", since = "1.11.0")]
708 impl Error for fmt::Error {
710 fn description(&self) -> &str {
711 "an error occurred when formatting an argument"
715 #[stable(feature = "try_borrow", since = "1.13.0")]
716 impl Error for cell::BorrowError {
718 fn description(&self) -> &str {
719 "already mutably borrowed"
723 #[stable(feature = "try_borrow", since = "1.13.0")]
724 impl Error for cell::BorrowMutError {
726 fn description(&self) -> &str {
731 #[stable(feature = "try_from", since = "1.34.0")]
732 impl Error for char::CharTryFromError {
734 fn description(&self) -> &str {
735 "converted integer out of range for `char`"
739 #[stable(feature = "char_from_str", since = "1.20.0")]
740 impl Error for char::ParseCharError {
742 fn description(&self) -> &str {
747 #[stable(feature = "try_reserve", since = "1.57.0")]
748 impl Error for alloc::collections::TryReserveError {}
750 #[unstable(feature = "duration_checked_float", issue = "83400")]
751 impl Error for time::FromFloatSecsError {}
753 #[stable(feature = "rust1", since = "1.0.0")]
754 impl Error for alloc::ffi::NulError {
756 fn description(&self) -> &str {
757 "nul byte found in data"
761 #[stable(feature = "rust1", since = "1.0.0")]
762 impl From<alloc::ffi::NulError> for io::Error {
763 /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
764 fn from(_: alloc::ffi::NulError) -> io::Error {
765 io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
769 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
770 impl Error for core::ffi::FromBytesWithNulError {
772 fn description(&self) -> &str {
777 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
778 impl Error for core::ffi::FromBytesUntilNulError {}
780 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
781 impl Error for alloc::ffi::FromVecWithNulError {}
783 #[stable(feature = "cstring_into", since = "1.7.0")]
784 impl Error for alloc::ffi::IntoStringError {
786 fn description(&self) -> &str {
787 "C string contained non-utf8 bytes"
790 fn source(&self) -> Option<&(dyn Error + 'static)> {
791 Some(self.__source())
795 // Copied from `any.rs`.
796 impl dyn Error + 'static {
797 /// Returns `true` if the inner type is the same as `T`.
798 #[stable(feature = "error_downcast", since = "1.3.0")]
800 pub fn is<T: Error + 'static>(&self) -> bool {
801 // Get `TypeId` of the type this function is instantiated with.
802 let t = TypeId::of::<T>();
804 // Get `TypeId` of the type in the trait object (`self`).
805 let concrete = self.type_id(private::Internal);
807 // Compare both `TypeId`s on equality.
811 /// Returns some reference to the inner value if it is of type `T`, or
812 /// `None` if it isn't.
813 #[stable(feature = "error_downcast", since = "1.3.0")]
815 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
817 unsafe { Some(&*(self as *const dyn Error as *const T)) }
823 /// Returns some mutable reference to the inner value if it is of type `T`, or
824 /// `None` if it isn't.
825 #[stable(feature = "error_downcast", since = "1.3.0")]
827 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
829 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
836 impl dyn Error + 'static + Send {
837 /// Forwards to the method defined on the type `dyn Error`.
838 #[stable(feature = "error_downcast", since = "1.3.0")]
840 pub fn is<T: Error + 'static>(&self) -> bool {
841 <dyn Error + 'static>::is::<T>(self)
844 /// Forwards to the method defined on the type `dyn Error`.
845 #[stable(feature = "error_downcast", since = "1.3.0")]
847 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
848 <dyn Error + 'static>::downcast_ref::<T>(self)
851 /// Forwards to the method defined on the type `dyn Error`.
852 #[stable(feature = "error_downcast", since = "1.3.0")]
854 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
855 <dyn Error + 'static>::downcast_mut::<T>(self)
859 impl dyn Error + 'static + Send + Sync {
860 /// Forwards to the method defined on the type `dyn Error`.
861 #[stable(feature = "error_downcast", since = "1.3.0")]
863 pub fn is<T: Error + 'static>(&self) -> bool {
864 <dyn Error + 'static>::is::<T>(self)
867 /// Forwards to the method defined on the type `dyn Error`.
868 #[stable(feature = "error_downcast", since = "1.3.0")]
870 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
871 <dyn Error + 'static>::downcast_ref::<T>(self)
874 /// Forwards to the method defined on the type `dyn Error`.
875 #[stable(feature = "error_downcast", since = "1.3.0")]
877 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
878 <dyn Error + 'static>::downcast_mut::<T>(self)
884 #[stable(feature = "error_downcast", since = "1.3.0")]
885 /// Attempts to downcast the box to a concrete type.
886 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
889 let raw: *mut dyn Error = Box::into_raw(self);
890 Ok(Box::from_raw(raw as *mut T))
897 /// Returns an iterator starting with the current error and continuing with
898 /// recursively calling [`Error::source`].
900 /// If you want to omit the current error and only use its sources,
906 /// #![feature(error_iter)]
907 /// use std::error::Error;
914 /// struct B(Option<Box<dyn Error + 'static>>);
916 /// impl fmt::Display for A {
917 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
922 /// impl fmt::Display for B {
923 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
928 /// impl Error for A {}
930 /// impl Error for B {
931 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
932 /// self.0.as_ref().map(|e| e.as_ref())
936 /// let b = B(Some(Box::new(A)));
938 /// // let err : Box<Error> = b.into(); // or
939 /// let err = &b as &(dyn Error);
941 /// let mut iter = err.chain();
943 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
944 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
945 /// assert!(iter.next().is_none());
946 /// assert!(iter.next().is_none());
948 #[unstable(feature = "error_iter", issue = "58520")]
950 pub fn chain(&self) -> Chain<'_> {
951 Chain { current: Some(self) }
955 /// An iterator over an [`Error`] and its sources.
957 /// If you want to omit the initial error and only process
958 /// its sources, use `skip(1)`.
959 #[unstable(feature = "error_iter", issue = "58520")]
960 #[derive(Clone, Debug)]
961 pub struct Chain<'a> {
962 current: Option<&'a (dyn Error + 'static)>,
965 #[unstable(feature = "error_iter", issue = "58520")]
966 impl<'a> Iterator for Chain<'a> {
967 type Item = &'a (dyn Error + 'static);
969 fn next(&mut self) -> Option<Self::Item> {
970 let current = self.current;
971 self.current = self.current.and_then(Error::source);
976 impl dyn Error + Send {
978 #[stable(feature = "error_downcast", since = "1.3.0")]
979 /// Attempts to downcast the box to a concrete type.
980 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
981 let err: Box<dyn Error> = self;
982 <dyn Error>::downcast(err).map_err(|s| unsafe {
983 // Reapply the `Send` marker.
984 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
989 impl dyn Error + Send + Sync {
991 #[stable(feature = "error_downcast", since = "1.3.0")]
992 /// Attempts to downcast the box to a concrete type.
993 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
994 let err: Box<dyn Error> = self;
995 <dyn Error>::downcast(err).map_err(|s| unsafe {
996 // Reapply the `Send + Sync` marker.
997 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
1002 /// An error reporter that prints an error and its sources.
1004 /// Report also exposes configuration options for formatting the error chain, either entirely on a
1005 /// single line, or in multi-line format with each cause in the error chain on a new line.
1007 /// `Report` only requires that the wrapped error implement `Error`. It doesn't require that the
1008 /// wrapped error be `Send`, `Sync`, or `'static`.
1013 /// #![feature(error_reporter)]
1014 /// use std::error::{Error, Report};
1017 /// #[derive(Debug)]
1018 /// struct SuperError {
1019 /// source: SuperErrorSideKick,
1022 /// impl fmt::Display for SuperError {
1023 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024 /// write!(f, "SuperError is here!")
1028 /// impl Error for SuperError {
1029 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
1030 /// Some(&self.source)
1034 /// #[derive(Debug)]
1035 /// struct SuperErrorSideKick;
1037 /// impl fmt::Display for SuperErrorSideKick {
1038 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1039 /// write!(f, "SuperErrorSideKick is here!")
1043 /// impl Error for SuperErrorSideKick {}
1045 /// fn get_super_error() -> Result<(), SuperError> {
1046 /// Err(SuperError { source: SuperErrorSideKick })
1050 /// match get_super_error() {
1051 /// Err(e) => println!("Error: {}", Report::new(e)),
1052 /// _ => println!("No error"),
1057 /// This example produces the following output:
1060 /// Error: SuperError is here!: SuperErrorSideKick is here!
1063 /// ## Output consistency
1065 /// Report prints the same output via `Display` and `Debug`, so it works well with
1066 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
1069 /// #![feature(error_reporter)]
1070 /// use std::error::Report;
1071 /// # use std::error::Error;
1073 /// # #[derive(Debug)]
1074 /// # struct SuperError {
1075 /// # source: SuperErrorSideKick,
1077 /// # impl fmt::Display for SuperError {
1078 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1079 /// # write!(f, "SuperError is here!")
1082 /// # impl Error for SuperError {
1083 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1084 /// # Some(&self.source)
1087 /// # #[derive(Debug)]
1088 /// # struct SuperErrorSideKick;
1089 /// # impl fmt::Display for SuperErrorSideKick {
1090 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1091 /// # write!(f, "SuperErrorSideKick is here!")
1094 /// # impl Error for SuperErrorSideKick {}
1095 /// # fn get_super_error() -> Result<(), SuperError> {
1096 /// # Err(SuperError { source: SuperErrorSideKick })
1099 /// get_super_error().map_err(Report::new).unwrap();
1102 /// This example produces the following output:
1105 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
1106 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1109 /// ## Return from `main`
1111 /// `Report` also implements `From` for all types that implement [`Error`]; this when combined with
1112 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
1116 /// #![feature(error_reporter)]
1117 /// use std::error::Report;
1118 /// # use std::error::Error;
1120 /// # #[derive(Debug)]
1121 /// # struct SuperError {
1122 /// # source: SuperErrorSideKick,
1124 /// # impl fmt::Display for SuperError {
1125 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1126 /// # write!(f, "SuperError is here!")
1129 /// # impl Error for SuperError {
1130 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1131 /// # Some(&self.source)
1134 /// # #[derive(Debug)]
1135 /// # struct SuperErrorSideKick;
1136 /// # impl fmt::Display for SuperErrorSideKick {
1137 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138 /// # write!(f, "SuperErrorSideKick is here!")
1141 /// # impl Error for SuperErrorSideKick {}
1142 /// # fn get_super_error() -> Result<(), SuperError> {
1143 /// # Err(SuperError { source: SuperErrorSideKick })
1146 /// fn main() -> Result<(), Report> {
1147 /// get_super_error()?;
1152 /// This example produces the following output:
1155 /// Error: SuperError is here!: SuperErrorSideKick is here!
1158 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1159 /// output format. If you want to make sure your `Report`s are pretty printed and include backtrace
1160 /// you will need to manually convert and enable those flags.
1163 /// #![feature(error_reporter)]
1164 /// use std::error::Report;
1165 /// # use std::error::Error;
1167 /// # #[derive(Debug)]
1168 /// # struct SuperError {
1169 /// # source: SuperErrorSideKick,
1171 /// # impl fmt::Display for SuperError {
1172 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1173 /// # write!(f, "SuperError is here!")
1176 /// # impl Error for SuperError {
1177 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1178 /// # Some(&self.source)
1181 /// # #[derive(Debug)]
1182 /// # struct SuperErrorSideKick;
1183 /// # impl fmt::Display for SuperErrorSideKick {
1184 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1185 /// # write!(f, "SuperErrorSideKick is here!")
1188 /// # impl Error for SuperErrorSideKick {}
1189 /// # fn get_super_error() -> Result<(), SuperError> {
1190 /// # Err(SuperError { source: SuperErrorSideKick })
1193 /// fn main() -> Result<(), Report> {
1194 /// get_super_error()
1195 /// .map_err(Report::from)
1196 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1201 /// This example produces the following output:
1204 /// Error: SuperError is here!
1207 /// SuperErrorSideKick is here!
1209 #[unstable(feature = "error_reporter", issue = "90172")]
1210 pub struct Report<E = Box<dyn Error>> {
1211 /// The error being reported.
1213 /// Whether a backtrace should be included as part of the report.
1214 show_backtrace: bool,
1215 /// Whether the report should be pretty-printed.
1223 /// Create a new `Report` from an input error.
1224 #[unstable(feature = "error_reporter", issue = "90172")]
1225 pub fn new(error: E) -> Report<E> {
1231 /// Enable pretty-printing the report across multiple lines.
1236 /// #![feature(error_reporter)]
1237 /// use std::error::Report;
1238 /// # use std::error::Error;
1240 /// # #[derive(Debug)]
1241 /// # struct SuperError {
1242 /// # source: SuperErrorSideKick,
1244 /// # impl fmt::Display for SuperError {
1245 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1246 /// # write!(f, "SuperError is here!")
1249 /// # impl Error for SuperError {
1250 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1251 /// # Some(&self.source)
1254 /// # #[derive(Debug)]
1255 /// # struct SuperErrorSideKick;
1256 /// # impl fmt::Display for SuperErrorSideKick {
1257 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 /// # write!(f, "SuperErrorSideKick is here!")
1261 /// # impl Error for SuperErrorSideKick {}
1263 /// let error = SuperError { source: SuperErrorSideKick };
1264 /// let report = Report::new(error).pretty(true);
1265 /// eprintln!("Error: {report:?}");
1268 /// This example produces the following output:
1271 /// Error: SuperError is here!
1274 /// SuperErrorSideKick is here!
1277 /// When there are multiple source errors the causes will be numbered in order of iteration
1278 /// starting from the outermost error.
1281 /// #![feature(error_reporter)]
1282 /// use std::error::Report;
1283 /// # use std::error::Error;
1285 /// # #[derive(Debug)]
1286 /// # struct SuperError {
1287 /// # source: SuperErrorSideKick,
1289 /// # impl fmt::Display for SuperError {
1290 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1291 /// # write!(f, "SuperError is here!")
1294 /// # impl Error for SuperError {
1295 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1296 /// # Some(&self.source)
1299 /// # #[derive(Debug)]
1300 /// # struct SuperErrorSideKick {
1301 /// # source: SuperErrorSideKickSideKick,
1303 /// # impl fmt::Display for SuperErrorSideKick {
1304 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1305 /// # write!(f, "SuperErrorSideKick is here!")
1308 /// # impl Error for SuperErrorSideKick {
1309 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1310 /// # Some(&self.source)
1313 /// # #[derive(Debug)]
1314 /// # struct SuperErrorSideKickSideKick;
1315 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1316 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1317 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1320 /// # impl Error for SuperErrorSideKickSideKick { }
1322 /// let source = SuperErrorSideKickSideKick;
1323 /// let source = SuperErrorSideKick { source };
1324 /// let error = SuperError { source };
1325 /// let report = Report::new(error).pretty(true);
1326 /// eprintln!("Error: {report:?}");
1329 /// This example produces the following output:
1332 /// Error: SuperError is here!
1335 /// 0: SuperErrorSideKick is here!
1336 /// 1: SuperErrorSideKickSideKick is here!
1338 #[unstable(feature = "error_reporter", issue = "90172")]
1339 pub fn pretty(mut self, pretty: bool) -> Self {
1340 self.pretty = pretty;
1344 /// Display backtrace if available when using pretty output format.
1348 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1349 /// outermost error. In this example it will display the backtrace from the second error in the
1350 /// chain, `SuperErrorSideKick`.
1353 /// #![feature(error_reporter)]
1354 /// #![feature(backtrace)]
1355 /// # use std::error::Error;
1357 /// use std::error::Report;
1358 /// use std::backtrace::Backtrace;
1360 /// # #[derive(Debug)]
1361 /// # struct SuperError {
1362 /// # source: SuperErrorSideKick,
1364 /// # impl fmt::Display for SuperError {
1365 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1366 /// # write!(f, "SuperError is here!")
1369 /// # impl Error for SuperError {
1370 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1371 /// # Some(&self.source)
1374 /// #[derive(Debug)]
1375 /// struct SuperErrorSideKick {
1376 /// backtrace: Backtrace,
1379 /// impl SuperErrorSideKick {
1380 /// fn new() -> SuperErrorSideKick {
1381 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1385 /// impl Error for SuperErrorSideKick {
1386 /// fn backtrace(&self) -> Option<&Backtrace> {
1387 /// Some(&self.backtrace)
1391 /// // The rest of the example is unchanged ...
1392 /// # impl fmt::Display for SuperErrorSideKick {
1393 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1394 /// # write!(f, "SuperErrorSideKick is here!")
1398 /// let source = SuperErrorSideKick::new();
1399 /// let error = SuperError { source };
1400 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1401 /// eprintln!("Error: {report:?}");
1404 /// This example produces something similar to the following output:
1407 /// Error: SuperError is here!
1410 /// SuperErrorSideKick is here!
1412 /// Stack backtrace:
1413 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1414 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1415 /// 2: rust_out::main
1416 /// 3: core::ops::function::FnOnce::call_once
1417 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1418 /// 5: std::rt::lang_start::{{closure}}
1419 /// 6: std::panicking::try
1420 /// 7: std::rt::lang_start_internal
1421 /// 8: std::rt::lang_start
1423 /// 10: __libc_start_main
1426 #[unstable(feature = "error_reporter", issue = "90172")]
1427 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1428 self.show_backtrace = show_backtrace;
1437 fn backtrace(&self) -> Option<&Backtrace> {
1438 // have to grab the backtrace on the first error directly since that error may not be
1440 let backtrace = self.error.backtrace();
1441 let backtrace = backtrace.or_else(|| {
1444 .map(|source| source.chain().find_map(|source| source.backtrace()))
1450 /// Format the report as a single line.
1451 #[unstable(feature = "error_reporter", issue = "90172")]
1452 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 write!(f, "{}", self.error)?;
1455 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1457 for cause in sources {
1458 write!(f, ": {cause}")?;
1464 /// Format the report as multiple lines, with each error cause on its own line.
1465 #[unstable(feature = "error_reporter", issue = "90172")]
1466 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 let error = &self.error;
1469 write!(f, "{error}")?;
1471 if let Some(cause) = error.source() {
1472 write!(f, "\n\nCaused by:")?;
1474 let multiple = cause.source().is_some();
1476 for (ind, error) in cause.chain().enumerate() {
1478 let mut indented = Indented { inner: f };
1480 write!(indented, "{ind: >4}: {error}")?;
1482 write!(indented, " {error}")?;
1487 if self.show_backtrace {
1488 let backtrace = self.backtrace();
1490 if let Some(backtrace) = backtrace {
1491 let backtrace = backtrace.to_string();
1493 f.write_str("\n\nStack backtrace:\n")?;
1494 f.write_str(backtrace.trim_end())?;
1502 impl Report<Box<dyn Error>> {
1503 fn backtrace(&self) -> Option<&Backtrace> {
1504 // have to grab the backtrace on the first error directly since that error may not be
1506 let backtrace = self.error.backtrace();
1507 let backtrace = backtrace.or_else(|| {
1510 .map(|source| source.chain().find_map(|source| source.backtrace()))
1516 /// Format the report as a single line.
1517 #[unstable(feature = "error_reporter", issue = "90172")]
1518 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1519 write!(f, "{}", self.error)?;
1521 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1523 for cause in sources {
1524 write!(f, ": {cause}")?;
1530 /// Format the report as multiple lines, with each error cause on its own line.
1531 #[unstable(feature = "error_reporter", issue = "90172")]
1532 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 let error = &self.error;
1535 write!(f, "{error}")?;
1537 if let Some(cause) = error.source() {
1538 write!(f, "\n\nCaused by:")?;
1540 let multiple = cause.source().is_some();
1542 for (ind, error) in cause.chain().enumerate() {
1544 let mut indented = Indented { inner: f };
1546 write!(indented, "{ind: >4}: {error}")?;
1548 write!(indented, " {error}")?;
1553 if self.show_backtrace {
1554 let backtrace = self.backtrace();
1556 if let Some(backtrace) = backtrace {
1557 let backtrace = backtrace.to_string();
1559 f.write_str("\n\nStack backtrace:\n")?;
1560 f.write_str(backtrace.trim_end())?;
1568 #[unstable(feature = "error_reporter", issue = "90172")]
1569 impl<E> From<E> for Report<E>
1573 fn from(error: E) -> Self {
1574 Report { error, show_backtrace: false, pretty: false }
1578 #[unstable(feature = "error_reporter", issue = "90172")]
1579 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1583 fn from(error: E) -> Self {
1584 let error = box error;
1585 Report { error, show_backtrace: false, pretty: false }
1589 #[unstable(feature = "error_reporter", issue = "90172")]
1590 impl<E> fmt::Display for Report<E>
1594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1595 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1599 #[unstable(feature = "error_reporter", issue = "90172")]
1600 impl fmt::Display for Report<Box<dyn Error>> {
1601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1602 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1606 // This type intentionally outputs the same format for `Display` and `Debug`for
1607 // situations where you unwrap a `Report` or return it from main.
1608 #[unstable(feature = "error_reporter", issue = "90172")]
1609 impl<E> fmt::Debug for Report<E>
1611 Report<E>: fmt::Display,
1613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1614 fmt::Display::fmt(self, f)
1618 /// Wrapper type for indenting the inner source.
1619 struct Indented<'a, D> {
1623 impl<T> Write for Indented<'_, T>
1627 fn write_str(&mut self, s: &str) -> fmt::Result {
1628 for (i, line) in s.split('\n').enumerate() {
1630 self.inner.write_char('\n')?;
1631 self.inner.write_str(" ")?;
1634 self.inner.write_str(line)?;