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]`] (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 propagation 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 //! panick, 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 hook]: crate::panic::set_hook
126 //! [`set_hook`]: crate::panic::set_hook
127 //! [`take_hook`]: crate::panic::take_hook
128 //! [`PanicInfo`]: crate::panic::PanicInfo
129 //! [`panic_any`]: crate::panic::panic_any
130 //! [`#[panic_handler]`]: https://doc.rust-lang.org/nomicon/panic-handler.html
131 //! [`catch_unwind`]: crate::panic::catch_unwind
132 //! [`resume_unwind`]: crate::panic::resume_unwind
133 //! [`Termination`]: crate::process::Termination
134 //! [`Try`]: crate::ops::Try
135 //! [`downcast`]: crate::error::Error
137 #![stable(feature = "rust1", since = "1.0.0")]
139 // A note about crates and the facade:
141 // Originally, the `Error` trait was defined in libcore, and the impls
142 // were scattered about. However, coherence objected to this
143 // arrangement, because to create the blanket impls for `Box` required
144 // knowing that `&str: !Error`, and we have no means to deal with that
145 // sort of conflict just now. Therefore, for the time being, we have
146 // moved the `Error` trait into libstd. As we evolve a sol'n to the
147 // coherence challenge (e.g., specialization, neg impls, etc) we can
148 // reconsider what crate these items belong in.
154 use core::convert::Infallible;
156 use crate::alloc::{AllocError, LayoutError};
157 use crate::any::TypeId;
158 use crate::backtrace::Backtrace;
159 use crate::borrow::Cow;
162 use crate::fmt::{self, Debug, Display, Write};
163 use crate::mem::transmute;
167 use crate::sync::Arc;
170 /// `Error` is a trait representing the basic expectations for error values,
171 /// i.e., values of type `E` in [`Result<T, E>`].
173 /// Errors must describe themselves through the [`Display`] and [`Debug`]
174 /// traits. Error messages are typically concise lowercase sentences without
175 /// trailing punctuation:
178 /// let err = "NaN".parse::<u32>().unwrap_err();
179 /// assert_eq!(err.to_string(), "invalid digit found in string");
182 /// Errors may provide cause chain information. [`Error::source()`] is generally
183 /// used when errors cross "abstraction boundaries". If one module must report
184 /// an error that is caused by an error from a lower-level module, it can allow
185 /// accessing that error via [`Error::source()`]. This makes it possible for the
186 /// high-level module to provide its own errors while also revealing some of the
187 /// implementation for debugging via `source` chains.
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub trait Error: Debug + Display {
190 /// The lower-level source of this error, if any.
195 /// use std::error::Error;
199 /// struct SuperError {
200 /// source: SuperErrorSideKick,
203 /// impl fmt::Display for SuperError {
204 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 /// write!(f, "SuperError is here!")
209 /// impl Error for SuperError {
210 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
211 /// Some(&self.source)
216 /// struct SuperErrorSideKick;
218 /// impl fmt::Display for SuperErrorSideKick {
219 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 /// write!(f, "SuperErrorSideKick is here!")
224 /// impl Error for SuperErrorSideKick {}
226 /// fn get_super_error() -> Result<(), SuperError> {
227 /// Err(SuperError { source: SuperErrorSideKick })
231 /// match get_super_error() {
233 /// println!("Error: {e}");
234 /// println!("Caused by: {}", e.source().unwrap());
236 /// _ => println!("No error"),
240 #[stable(feature = "error_source", since = "1.30.0")]
241 fn source(&self) -> Option<&(dyn Error + 'static)> {
245 /// Gets the `TypeId` of `self`.
248 feature = "error_type_id",
249 reason = "this is memory-unsafe to override in user code",
252 fn type_id(&self, _: private::Internal) -> TypeId
259 /// Returns a stack backtrace, if available, of where this error occurred.
261 /// This function allows inspecting the location, in code, of where an error
262 /// happened. The returned `Backtrace` contains information about the stack
263 /// trace of the OS thread of execution of where the error originated from.
265 /// Note that not all errors contain a `Backtrace`. Also note that a
266 /// `Backtrace` may actually be empty. For more information consult the
267 /// `Backtrace` type itself.
268 #[unstable(feature = "backtrace", issue = "53487")]
269 fn backtrace(&self) -> Option<&Backtrace> {
274 /// if let Err(e) = "xc".parse::<u32>() {
275 /// // Print `e` itself, no need for description().
276 /// eprintln!("Error: {e}");
279 #[stable(feature = "rust1", since = "1.0.0")]
280 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
281 fn description(&self) -> &str {
282 "description() is deprecated; use Display"
285 #[stable(feature = "rust1", since = "1.0.0")]
288 reason = "replaced by Error::source, which can support downcasting"
290 #[allow(missing_docs)]
291 fn cause(&self) -> Option<&dyn Error> {
297 // This is a hack to prevent `type_id` from being overridden by `Error`
298 // implementations, since that can enable unsound downcasting.
299 #[unstable(feature = "error_type_id", issue = "60784")]
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
306 /// Converts a type of [`Error`] into a box of dyn [`Error`].
311 /// use std::error::Error;
318 /// impl fmt::Display for AnError {
319 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 /// write!(f, "An error")
324 /// impl Error for AnError {}
326 /// let an_error = AnError;
327 /// assert!(0 == mem::size_of_val(&an_error));
328 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
329 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
331 fn from(err: E) -> Box<dyn Error + 'a> {
336 #[stable(feature = "rust1", since = "1.0.0")]
337 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
338 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
339 /// dyn [`Error`] + [`Send`] + [`Sync`].
344 /// use std::error::Error;
351 /// impl fmt::Display for AnError {
352 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353 /// write!(f, "An error")
357 /// impl Error for AnError {}
359 /// unsafe impl Send for AnError {}
361 /// unsafe impl Sync for AnError {}
363 /// let an_error = AnError;
364 /// assert!(0 == mem::size_of_val(&an_error));
365 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
367 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
369 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl From<String> for Box<dyn Error + Send + Sync> {
376 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
381 /// use std::error::Error;
384 /// let a_string_error = "a string error".to_string();
385 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
387 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
390 fn from(err: String) -> Box<dyn Error + Send + Sync> {
391 struct StringError(String);
393 impl Error for StringError {
395 fn description(&self) -> &str {
400 impl Display for StringError {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 Display::fmt(&self.0, f)
406 // Purposefully skip printing "StringError(..)"
407 impl Debug for StringError {
408 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409 Debug::fmt(&self.0, f)
413 Box::new(StringError(err))
417 #[stable(feature = "string_box_error", since = "1.6.0")]
418 impl From<String> for Box<dyn Error> {
419 /// Converts a [`String`] into a box of dyn [`Error`].
424 /// use std::error::Error;
427 /// let a_string_error = "a string error".to_string();
428 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
429 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
431 fn from(str_err: String) -> Box<dyn Error> {
432 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
433 let err2: Box<dyn Error> = err1;
438 #[stable(feature = "rust1", since = "1.0.0")]
439 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
440 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
442 /// [`str`]: prim@str
447 /// use std::error::Error;
450 /// let a_str_error = "a str error";
451 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
453 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
456 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
457 From::from(String::from(err))
461 #[stable(feature = "string_box_error", since = "1.6.0")]
462 impl From<&str> for Box<dyn Error> {
463 /// Converts a [`str`] into a box of dyn [`Error`].
465 /// [`str`]: prim@str
470 /// use std::error::Error;
473 /// let a_str_error = "a str error";
474 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
475 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
477 fn from(err: &str) -> Box<dyn Error> {
478 From::from(String::from(err))
482 #[stable(feature = "cow_box_error", since = "1.22.0")]
483 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
484 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
489 /// use std::error::Error;
491 /// use std::borrow::Cow;
493 /// let a_cow_str_error = Cow::from("a str error");
494 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
496 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
498 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
499 From::from(String::from(err))
503 #[stable(feature = "cow_box_error", since = "1.22.0")]
504 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
505 /// Converts a [`Cow`] into a box of dyn [`Error`].
510 /// use std::error::Error;
512 /// use std::borrow::Cow;
514 /// let a_cow_str_error = Cow::from("a str error");
515 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
516 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
518 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
519 From::from(String::from(err))
523 #[unstable(feature = "never_type", issue = "35121")]
527 feature = "allocator_api",
528 reason = "the precise API and guarantees it provides may be tweaked.",
531 impl Error for AllocError {}
533 #[stable(feature = "alloc_layout", since = "1.28.0")]
534 impl Error for LayoutError {}
536 #[stable(feature = "rust1", since = "1.0.0")]
537 impl Error for str::ParseBoolError {
539 fn description(&self) -> &str {
540 "failed to parse bool"
544 #[stable(feature = "rust1", since = "1.0.0")]
545 impl Error for str::Utf8Error {
547 fn description(&self) -> &str {
548 "invalid utf-8: corrupt contents"
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl Error for num::ParseIntError {
555 fn description(&self) -> &str {
560 #[stable(feature = "try_from", since = "1.34.0")]
561 impl Error for num::TryFromIntError {
563 fn description(&self) -> &str {
568 #[stable(feature = "try_from", since = "1.34.0")]
569 impl Error for array::TryFromSliceError {
571 fn description(&self) -> &str {
576 #[stable(feature = "rust1", since = "1.0.0")]
577 impl Error for num::ParseFloatError {
579 fn description(&self) -> &str {
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl Error for string::FromUtf8Error {
587 fn description(&self) -> &str {
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl Error for string::FromUtf16Error {
595 fn description(&self) -> &str {
600 #[stable(feature = "str_parse_error2", since = "1.8.0")]
601 impl Error for Infallible {
602 fn description(&self) -> &str {
607 #[stable(feature = "decode_utf16", since = "1.9.0")]
608 impl Error for char::DecodeUtf16Error {
610 fn description(&self) -> &str {
611 "unpaired surrogate found"
615 #[stable(feature = "u8_from_char", since = "1.59.0")]
616 impl Error for char::TryFromCharError {}
618 #[unstable(feature = "map_try_insert", issue = "82766")]
619 impl<'a, K: Debug + Ord, V: Debug> Error
620 for crate::collections::btree_map::OccupiedError<'a, K, V>
623 fn description(&self) -> &str {
628 #[unstable(feature = "map_try_insert", issue = "82766")]
629 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
631 fn description(&self) -> &str {
636 #[stable(feature = "box_error", since = "1.8.0")]
637 impl<T: Error> Error for Box<T> {
638 #[allow(deprecated, deprecated_in_future)]
639 fn description(&self) -> &str {
640 Error::description(&**self)
644 fn cause(&self) -> Option<&dyn Error> {
645 Error::cause(&**self)
648 fn source(&self) -> Option<&(dyn Error + 'static)> {
649 Error::source(&**self)
653 #[unstable(feature = "thin_box", issue = "92791")]
654 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
655 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
656 use core::ops::Deref;
657 self.deref().source()
661 #[stable(feature = "error_by_ref", since = "1.51.0")]
662 impl<'a, T: Error + ?Sized> Error for &'a T {
663 #[allow(deprecated, deprecated_in_future)]
664 fn description(&self) -> &str {
665 Error::description(&**self)
669 fn cause(&self) -> Option<&dyn Error> {
670 Error::cause(&**self)
673 fn source(&self) -> Option<&(dyn Error + 'static)> {
674 Error::source(&**self)
677 fn backtrace(&self) -> Option<&Backtrace> {
678 Error::backtrace(&**self)
682 #[stable(feature = "arc_error", since = "1.52.0")]
683 impl<T: Error + ?Sized> Error for Arc<T> {
684 #[allow(deprecated, deprecated_in_future)]
685 fn description(&self) -> &str {
686 Error::description(&**self)
690 fn cause(&self) -> Option<&dyn Error> {
691 Error::cause(&**self)
694 fn source(&self) -> Option<&(dyn Error + 'static)> {
695 Error::source(&**self)
698 fn backtrace(&self) -> Option<&Backtrace> {
699 Error::backtrace(&**self)
703 #[stable(feature = "fmt_error", since = "1.11.0")]
704 impl Error for fmt::Error {
706 fn description(&self) -> &str {
707 "an error occurred when formatting an argument"
711 #[stable(feature = "try_borrow", since = "1.13.0")]
712 impl Error for cell::BorrowError {
714 fn description(&self) -> &str {
715 "already mutably borrowed"
719 #[stable(feature = "try_borrow", since = "1.13.0")]
720 impl Error for cell::BorrowMutError {
722 fn description(&self) -> &str {
727 #[stable(feature = "try_from", since = "1.34.0")]
728 impl Error for char::CharTryFromError {
730 fn description(&self) -> &str {
731 "converted integer out of range for `char`"
735 #[stable(feature = "char_from_str", since = "1.20.0")]
736 impl Error for char::ParseCharError {
738 fn description(&self) -> &str {
743 #[stable(feature = "try_reserve", since = "1.57.0")]
744 impl Error for alloc::collections::TryReserveError {}
746 #[unstable(feature = "duration_checked_float", issue = "83400")]
747 impl Error for time::FromFloatSecsError {}
749 // Copied from `any.rs`.
750 impl dyn Error + 'static {
751 /// Returns `true` if the inner type is the same as `T`.
752 #[stable(feature = "error_downcast", since = "1.3.0")]
754 pub fn is<T: Error + 'static>(&self) -> bool {
755 // Get `TypeId` of the type this function is instantiated with.
756 let t = TypeId::of::<T>();
758 // Get `TypeId` of the type in the trait object (`self`).
759 let concrete = self.type_id(private::Internal);
761 // Compare both `TypeId`s on equality.
765 /// Returns some reference to the inner value if it is of type `T`, or
766 /// `None` if it isn't.
767 #[stable(feature = "error_downcast", since = "1.3.0")]
769 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
771 unsafe { Some(&*(self as *const dyn Error as *const T)) }
777 /// Returns some mutable reference to the inner value if it is of type `T`, or
778 /// `None` if it isn't.
779 #[stable(feature = "error_downcast", since = "1.3.0")]
781 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
783 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
790 impl dyn Error + 'static + Send {
791 /// Forwards to the method defined on the type `dyn Error`.
792 #[stable(feature = "error_downcast", since = "1.3.0")]
794 pub fn is<T: Error + 'static>(&self) -> bool {
795 <dyn Error + 'static>::is::<T>(self)
798 /// Forwards to the method defined on the type `dyn Error`.
799 #[stable(feature = "error_downcast", since = "1.3.0")]
801 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
802 <dyn Error + 'static>::downcast_ref::<T>(self)
805 /// Forwards to the method defined on the type `dyn Error`.
806 #[stable(feature = "error_downcast", since = "1.3.0")]
808 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
809 <dyn Error + 'static>::downcast_mut::<T>(self)
813 impl dyn Error + 'static + Send + Sync {
814 /// Forwards to the method defined on the type `dyn Error`.
815 #[stable(feature = "error_downcast", since = "1.3.0")]
817 pub fn is<T: Error + 'static>(&self) -> bool {
818 <dyn Error + 'static>::is::<T>(self)
821 /// Forwards to the method defined on the type `dyn Error`.
822 #[stable(feature = "error_downcast", since = "1.3.0")]
824 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
825 <dyn Error + 'static>::downcast_ref::<T>(self)
828 /// Forwards to the method defined on the type `dyn Error`.
829 #[stable(feature = "error_downcast", since = "1.3.0")]
831 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
832 <dyn Error + 'static>::downcast_mut::<T>(self)
838 #[stable(feature = "error_downcast", since = "1.3.0")]
839 /// Attempts to downcast the box to a concrete type.
840 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
843 let raw: *mut dyn Error = Box::into_raw(self);
844 Ok(Box::from_raw(raw as *mut T))
851 /// Returns an iterator starting with the current error and continuing with
852 /// recursively calling [`Error::source`].
854 /// If you want to omit the current error and only use its sources,
860 /// #![feature(error_iter)]
861 /// use std::error::Error;
868 /// struct B(Option<Box<dyn Error + 'static>>);
870 /// impl fmt::Display for A {
871 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 /// impl fmt::Display for B {
877 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 /// impl Error for A {}
884 /// impl Error for B {
885 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
886 /// self.0.as_ref().map(|e| e.as_ref())
890 /// let b = B(Some(Box::new(A)));
892 /// // let err : Box<Error> = b.into(); // or
893 /// let err = &b as &(dyn Error);
895 /// let mut iter = err.chain();
897 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
898 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
899 /// assert!(iter.next().is_none());
900 /// assert!(iter.next().is_none());
902 #[unstable(feature = "error_iter", issue = "58520")]
904 pub fn chain(&self) -> Chain<'_> {
905 Chain { current: Some(self) }
909 /// An iterator over an [`Error`] and its sources.
911 /// If you want to omit the initial error and only process
912 /// its sources, use `skip(1)`.
913 #[unstable(feature = "error_iter", issue = "58520")]
914 #[derive(Clone, Debug)]
915 pub struct Chain<'a> {
916 current: Option<&'a (dyn Error + 'static)>,
919 #[unstable(feature = "error_iter", issue = "58520")]
920 impl<'a> Iterator for Chain<'a> {
921 type Item = &'a (dyn Error + 'static);
923 fn next(&mut self) -> Option<Self::Item> {
924 let current = self.current;
925 self.current = self.current.and_then(Error::source);
930 impl dyn Error + Send {
932 #[stable(feature = "error_downcast", since = "1.3.0")]
933 /// Attempts to downcast the box to a concrete type.
934 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
935 let err: Box<dyn Error> = self;
936 <dyn Error>::downcast(err).map_err(|s| unsafe {
937 // Reapply the `Send` marker.
938 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
943 impl dyn Error + Send + Sync {
945 #[stable(feature = "error_downcast", since = "1.3.0")]
946 /// Attempts to downcast the box to a concrete type.
947 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
948 let err: Box<dyn Error> = self;
949 <dyn Error>::downcast(err).map_err(|s| unsafe {
950 // Reapply the `Send + Sync` marker.
951 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
956 /// An error reporter that print's an error and its sources.
958 /// Report also exposes configuration options for formatting the error chain, either entirely on a
959 /// single line, or in multi-line format with each cause in the error chain on a new line.
961 /// `Report` only requires that the wrapped error implements `Error`. It doesn't require that the
962 /// wrapped error be `Send`, `Sync`, or `'static`.
967 /// #![feature(error_reporter)]
968 /// use std::error::{Error, Report};
972 /// struct SuperError {
973 /// source: SuperErrorSideKick,
976 /// impl fmt::Display for SuperError {
977 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978 /// write!(f, "SuperError is here!")
982 /// impl Error for SuperError {
983 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
984 /// Some(&self.source)
989 /// struct SuperErrorSideKick;
991 /// impl fmt::Display for SuperErrorSideKick {
992 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
993 /// write!(f, "SuperErrorSideKick is here!")
997 /// impl Error for SuperErrorSideKick {}
999 /// fn get_super_error() -> Result<(), SuperError> {
1000 /// Err(SuperError { source: SuperErrorSideKick })
1004 /// match get_super_error() {
1005 /// Err(e) => println!("Error: {}", Report::new(e)),
1006 /// _ => println!("No error"),
1011 /// This example produces the following output:
1014 /// Error: SuperError is here!: SuperErrorSideKick is here!
1017 /// ## Output consistency
1019 /// Report prints the same output via `Display` and `Debug`, so it works well with
1020 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
1023 /// #![feature(error_reporter)]
1024 /// use std::error::Report;
1025 /// # use std::error::Error;
1027 /// # #[derive(Debug)]
1028 /// # struct SuperError {
1029 /// # source: SuperErrorSideKick,
1031 /// # impl fmt::Display for SuperError {
1032 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1033 /// # write!(f, "SuperError is here!")
1036 /// # impl Error for SuperError {
1037 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1038 /// # Some(&self.source)
1041 /// # #[derive(Debug)]
1042 /// # struct SuperErrorSideKick;
1043 /// # impl fmt::Display for SuperErrorSideKick {
1044 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1045 /// # write!(f, "SuperErrorSideKick is here!")
1048 /// # impl Error for SuperErrorSideKick {}
1049 /// # fn get_super_error() -> Result<(), SuperError> {
1050 /// # Err(SuperError { source: SuperErrorSideKick })
1053 /// get_super_error().map_err(Report::new).unwrap();
1056 /// This example produces the following output:
1059 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
1060 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1063 /// ## Return from `main`
1065 /// `Report` also implements `From` for all types that implement [`Error`], this when combined with
1066 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
1070 /// #![feature(error_reporter)]
1071 /// use std::error::Report;
1072 /// # use std::error::Error;
1074 /// # #[derive(Debug)]
1075 /// # struct SuperError {
1076 /// # source: SuperErrorSideKick,
1078 /// # impl fmt::Display for SuperError {
1079 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1080 /// # write!(f, "SuperError is here!")
1083 /// # impl Error for SuperError {
1084 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1085 /// # Some(&self.source)
1088 /// # #[derive(Debug)]
1089 /// # struct SuperErrorSideKick;
1090 /// # impl fmt::Display for SuperErrorSideKick {
1091 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1092 /// # write!(f, "SuperErrorSideKick is here!")
1095 /// # impl Error for SuperErrorSideKick {}
1096 /// # fn get_super_error() -> Result<(), SuperError> {
1097 /// # Err(SuperError { source: SuperErrorSideKick })
1100 /// fn main() -> Result<(), Report> {
1101 /// get_super_error()?;
1106 /// This example produces the following output:
1109 /// Error: SuperError is here!: SuperErrorSideKick is here!
1112 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1113 /// output format, if you want to make sure your `Report`s are pretty printed and include backtrace
1114 /// you will need to manually convert and enable those flags.
1117 /// #![feature(error_reporter)]
1118 /// use std::error::Report;
1119 /// # use std::error::Error;
1121 /// # #[derive(Debug)]
1122 /// # struct SuperError {
1123 /// # source: SuperErrorSideKick,
1125 /// # impl fmt::Display for SuperError {
1126 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1127 /// # write!(f, "SuperError is here!")
1130 /// # impl Error for SuperError {
1131 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1132 /// # Some(&self.source)
1135 /// # #[derive(Debug)]
1136 /// # struct SuperErrorSideKick;
1137 /// # impl fmt::Display for SuperErrorSideKick {
1138 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1139 /// # write!(f, "SuperErrorSideKick is here!")
1142 /// # impl Error for SuperErrorSideKick {}
1143 /// # fn get_super_error() -> Result<(), SuperError> {
1144 /// # Err(SuperError { source: SuperErrorSideKick })
1147 /// fn main() -> Result<(), Report> {
1148 /// get_super_error()
1149 /// .map_err(Report::from)
1150 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1155 /// This example produces the following output:
1158 /// Error: SuperError is here!
1161 /// SuperErrorSideKick is here!
1163 #[unstable(feature = "error_reporter", issue = "90172")]
1164 pub struct Report<E = Box<dyn Error>> {
1165 /// The error being reported.
1167 /// Whether a backtrace should be included as part of the report.
1168 show_backtrace: bool,
1169 /// Whether the report should be pretty-printed.
1177 /// Create a new `Report` from an input error.
1178 #[unstable(feature = "error_reporter", issue = "90172")]
1179 pub fn new(error: E) -> Report<E> {
1185 /// Enable pretty-printing the report across multiple lines.
1190 /// #![feature(error_reporter)]
1191 /// use std::error::Report;
1192 /// # use std::error::Error;
1194 /// # #[derive(Debug)]
1195 /// # struct SuperError {
1196 /// # source: SuperErrorSideKick,
1198 /// # impl fmt::Display for SuperError {
1199 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1200 /// # write!(f, "SuperError is here!")
1203 /// # impl Error for SuperError {
1204 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1205 /// # Some(&self.source)
1208 /// # #[derive(Debug)]
1209 /// # struct SuperErrorSideKick;
1210 /// # impl fmt::Display for SuperErrorSideKick {
1211 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1212 /// # write!(f, "SuperErrorSideKick is here!")
1215 /// # impl Error for SuperErrorSideKick {}
1217 /// let error = SuperError { source: SuperErrorSideKick };
1218 /// let report = Report::new(error).pretty(true);
1219 /// eprintln!("Error: {report:?}");
1222 /// This example produces the following output:
1225 /// Error: SuperError is here!
1228 /// SuperErrorSideKick is here!
1231 /// When there are multiple source errors the causes will be numbered in order of iteration
1232 /// starting from the outermost error.
1235 /// #![feature(error_reporter)]
1236 /// use std::error::Report;
1237 /// # use std::error::Error;
1239 /// # #[derive(Debug)]
1240 /// # struct SuperError {
1241 /// # source: SuperErrorSideKick,
1243 /// # impl fmt::Display for SuperError {
1244 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1245 /// # write!(f, "SuperError is here!")
1248 /// # impl Error for SuperError {
1249 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1250 /// # Some(&self.source)
1253 /// # #[derive(Debug)]
1254 /// # struct SuperErrorSideKick {
1255 /// # source: SuperErrorSideKickSideKick,
1257 /// # impl fmt::Display for SuperErrorSideKick {
1258 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1259 /// # write!(f, "SuperErrorSideKick is here!")
1262 /// # impl Error for SuperErrorSideKick {
1263 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1264 /// # Some(&self.source)
1267 /// # #[derive(Debug)]
1268 /// # struct SuperErrorSideKickSideKick;
1269 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1270 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1271 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1274 /// # impl Error for SuperErrorSideKickSideKick { }
1276 /// let source = SuperErrorSideKickSideKick;
1277 /// let source = SuperErrorSideKick { source };
1278 /// let error = SuperError { source };
1279 /// let report = Report::new(error).pretty(true);
1280 /// eprintln!("Error: {report:?}");
1283 /// This example produces the following output:
1286 /// Error: SuperError is here!
1289 /// 0: SuperErrorSideKick is here!
1290 /// 1: SuperErrorSideKickSideKick is here!
1292 #[unstable(feature = "error_reporter", issue = "90172")]
1293 pub fn pretty(mut self, pretty: bool) -> Self {
1294 self.pretty = pretty;
1298 /// Display backtrace if available when using pretty output format.
1302 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1303 /// outermost error. In this example it will display the backtrace from the second error in the
1304 /// chain, `SuperErrorSideKick`.
1307 /// #![feature(error_reporter)]
1308 /// #![feature(backtrace)]
1309 /// # use std::error::Error;
1311 /// use std::error::Report;
1312 /// use std::backtrace::Backtrace;
1314 /// # #[derive(Debug)]
1315 /// # struct SuperError {
1316 /// # source: SuperErrorSideKick,
1318 /// # impl fmt::Display for SuperError {
1319 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1320 /// # write!(f, "SuperError is here!")
1323 /// # impl Error for SuperError {
1324 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1325 /// # Some(&self.source)
1328 /// #[derive(Debug)]
1329 /// struct SuperErrorSideKick {
1330 /// backtrace: Backtrace,
1333 /// impl SuperErrorSideKick {
1334 /// fn new() -> SuperErrorSideKick {
1335 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1339 /// impl Error for SuperErrorSideKick {
1340 /// fn backtrace(&self) -> Option<&Backtrace> {
1341 /// Some(&self.backtrace)
1345 /// // The rest of the example is unchanged ...
1346 /// # impl fmt::Display for SuperErrorSideKick {
1347 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1348 /// # write!(f, "SuperErrorSideKick is here!")
1352 /// let source = SuperErrorSideKick::new();
1353 /// let error = SuperError { source };
1354 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1355 /// eprintln!("Error: {report:?}");
1358 /// This example produces something similar to the following output:
1361 /// Error: SuperError is here!
1364 /// SuperErrorSideKick is here!
1366 /// Stack backtrace:
1367 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1368 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1369 /// 2: rust_out::main
1370 /// 3: core::ops::function::FnOnce::call_once
1371 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1372 /// 5: std::rt::lang_start::{{closure}}
1373 /// 6: std::panicking::try
1374 /// 7: std::rt::lang_start_internal
1375 /// 8: std::rt::lang_start
1377 /// 10: __libc_start_main
1380 #[unstable(feature = "error_reporter", issue = "90172")]
1381 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1382 self.show_backtrace = show_backtrace;
1391 fn backtrace(&self) -> Option<&Backtrace> {
1392 // have to grab the backtrace on the first error directly since that error may not be
1394 let backtrace = self.error.backtrace();
1395 let backtrace = backtrace.or_else(|| {
1398 .map(|source| source.chain().find_map(|source| source.backtrace()))
1404 /// Format the report as a single line.
1405 #[unstable(feature = "error_reporter", issue = "90172")]
1406 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1407 write!(f, "{}", self.error)?;
1409 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1411 for cause in sources {
1412 write!(f, ": {cause}")?;
1418 /// Format the report as multiple lines, with each error cause on its own line.
1419 #[unstable(feature = "error_reporter", issue = "90172")]
1420 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1421 let error = &self.error;
1423 write!(f, "{error}")?;
1425 if let Some(cause) = error.source() {
1426 write!(f, "\n\nCaused by:")?;
1428 let multiple = cause.source().is_some();
1430 for (ind, error) in cause.chain().enumerate() {
1432 let mut indented = Indented { inner: f };
1434 write!(indented, "{ind: >4}: {error}")?;
1436 write!(indented, " {error}")?;
1441 if self.show_backtrace {
1442 let backtrace = self.backtrace();
1444 if let Some(backtrace) = backtrace {
1445 let backtrace = backtrace.to_string();
1447 f.write_str("\n\nStack backtrace:\n")?;
1448 f.write_str(backtrace.trim_end())?;
1456 impl Report<Box<dyn Error>> {
1457 fn backtrace(&self) -> Option<&Backtrace> {
1458 // have to grab the backtrace on the first error directly since that error may not be
1460 let backtrace = self.error.backtrace();
1461 let backtrace = backtrace.or_else(|| {
1464 .map(|source| source.chain().find_map(|source| source.backtrace()))
1470 /// Format the report as a single line.
1471 #[unstable(feature = "error_reporter", issue = "90172")]
1472 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1473 write!(f, "{}", self.error)?;
1475 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1477 for cause in sources {
1478 write!(f, ": {cause}")?;
1484 /// Format the report as multiple lines, with each error cause on its own line.
1485 #[unstable(feature = "error_reporter", issue = "90172")]
1486 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1487 let error = &self.error;
1489 write!(f, "{error}")?;
1491 if let Some(cause) = error.source() {
1492 write!(f, "\n\nCaused by:")?;
1494 let multiple = cause.source().is_some();
1496 for (ind, error) in cause.chain().enumerate() {
1498 let mut indented = Indented { inner: f };
1500 write!(indented, "{ind: >4}: {error}")?;
1502 write!(indented, " {error}")?;
1507 if self.show_backtrace {
1508 let backtrace = self.backtrace();
1510 if let Some(backtrace) = backtrace {
1511 let backtrace = backtrace.to_string();
1513 f.write_str("\n\nStack backtrace:\n")?;
1514 f.write_str(backtrace.trim_end())?;
1522 #[unstable(feature = "error_reporter", issue = "90172")]
1523 impl<E> From<E> for Report<E>
1527 fn from(error: E) -> Self {
1528 Report { error, show_backtrace: false, pretty: false }
1532 #[unstable(feature = "error_reporter", issue = "90172")]
1533 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1537 fn from(error: E) -> Self {
1538 let error = box error;
1539 Report { error, show_backtrace: false, pretty: false }
1543 #[unstable(feature = "error_reporter", issue = "90172")]
1544 impl<E> fmt::Display for Report<E>
1548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1549 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1553 #[unstable(feature = "error_reporter", issue = "90172")]
1554 impl fmt::Display for Report<Box<dyn Error>> {
1555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1556 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1560 // This type intentionally outputs the same format for `Display` and `Debug`for
1561 // situations where you unwrap a `Report` or return it from main.
1562 #[unstable(feature = "error_reporter", issue = "90172")]
1563 impl<E> fmt::Debug for Report<E>
1565 Report<E>: fmt::Display,
1567 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1568 fmt::Display::fmt(self, f)
1572 /// Wrapper type for indenting the inner source.
1573 struct Indented<'a, D> {
1577 impl<T> Write for Indented<'_, T>
1581 fn write_str(&mut self, s: &str) -> fmt::Result {
1582 for (i, line) in s.split('\n').enumerate() {
1584 self.inner.write_char('\n')?;
1585 self.inner.write_str(" ")?;
1588 self.inner.write_str(line)?;