1 #![doc = include_str!("../../core/src/error.md")]
2 #![stable(feature = "rust1", since = "1.0.0")]
4 // A note about crates and the facade:
6 // Originally, the `Error` trait was defined in libcore, and the impls
7 // were scattered about. However, coherence objected to this
8 // arrangement, because to create the blanket impls for `Box` required
9 // knowing that `&str: !Error`, and we have no means to deal with that
10 // sort of conflict just now. Therefore, for the time being, we have
11 // moved the `Error` trait into libstd. As we evolve a sol'n to the
12 // coherence challenge (e.g., specialization, neg impls, etc) we can
13 // reconsider what crate these items belong in.
21 use core::convert::Infallible;
24 use crate::alloc::{AllocError, LayoutError};
26 use crate::any::Demand;
28 use crate::any::{Provider, TypeId};
29 use crate::backtrace::Backtrace;
31 use crate::borrow::Cow;
37 use crate::fmt::Debug;
39 use crate::fmt::Display;
40 use crate::fmt::{self, Write};
44 use crate::mem::transmute;
56 #[cfg(not(bootstrap))]
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::error::Error;
60 /// `Error` is a trait representing the basic expectations for error values,
61 /// i.e., values of type `E` in [`Result<T, E>`].
63 /// Errors must describe themselves through the [`Display`] and [`Debug`]
64 /// traits. Error messages are typically concise lowercase sentences without
65 /// trailing punctuation:
68 /// let err = "NaN".parse::<u32>().unwrap_err();
69 /// assert_eq!(err.to_string(), "invalid digit found in string");
72 /// Errors may provide cause information. [`Error::source()`] is generally
73 /// used when errors cross "abstraction boundaries". If one module must report
74 /// an error that is caused by an error from a lower-level module, it can allow
75 /// accessing that error via [`Error::source()`]. This makes it possible for the
76 /// high-level module to provide its own errors while also revealing some of the
77 /// implementation for debugging.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 #[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
81 pub trait Error: Debug + Display {
82 /// The lower-level source of this error, if any.
87 /// use std::error::Error;
91 /// struct SuperError {
92 /// source: SuperErrorSideKick,
95 /// impl fmt::Display for SuperError {
96 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 /// write!(f, "SuperError is here!")
101 /// impl Error for SuperError {
102 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
103 /// Some(&self.source)
108 /// struct SuperErrorSideKick;
110 /// impl fmt::Display for SuperErrorSideKick {
111 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 /// write!(f, "SuperErrorSideKick is here!")
116 /// impl Error for SuperErrorSideKick {}
118 /// fn get_super_error() -> Result<(), SuperError> {
119 /// Err(SuperError { source: SuperErrorSideKick })
123 /// match get_super_error() {
125 /// println!("Error: {e}");
126 /// println!("Caused by: {}", e.source().unwrap());
128 /// _ => println!("No error"),
132 #[stable(feature = "error_source", since = "1.30.0")]
133 fn source(&self) -> Option<&(dyn Error + 'static)> {
137 /// Gets the `TypeId` of `self`.
140 feature = "error_type_id",
141 reason = "this is memory-unsafe to override in user code",
144 fn type_id(&self, _: private::Internal) -> TypeId
152 /// if let Err(e) = "xc".parse::<u32>() {
153 /// // Print `e` itself, no need for description().
154 /// eprintln!("Error: {e}");
157 #[stable(feature = "rust1", since = "1.0.0")]
158 #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")]
159 fn description(&self) -> &str {
160 "description() is deprecated; use Display"
163 #[stable(feature = "rust1", since = "1.0.0")]
166 note = "replaced by Error::source, which can support downcasting"
168 #[allow(missing_docs)]
169 fn cause(&self) -> Option<&dyn Error> {
173 /// Provides type based access to context intended for error reports.
175 /// Used in conjunction with [`Demand::provide_value`] and [`Demand::provide_ref`] to extract
176 /// references to member variables from `dyn Error` trait objects.
181 /// #![feature(provide_any)]
182 /// #![feature(error_generic_member_access)]
184 /// use core::any::Demand;
187 /// struct MyBacktrace {
191 /// impl MyBacktrace {
192 /// fn new() -> MyBacktrace {
199 /// struct SourceError {
203 /// impl fmt::Display for SourceError {
204 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 /// write!(f, "Example Source Error")
209 /// impl std::error::Error for SourceError {}
213 /// source: SourceError,
214 /// backtrace: MyBacktrace,
217 /// impl fmt::Display for Error {
218 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 /// write!(f, "Example Error")
223 /// impl std::error::Error for Error {
224 /// fn provide<'a>(&'a self, req: &mut Demand<'a>) {
226 /// .provide_ref::<MyBacktrace>(&self.backtrace)
227 /// .provide_ref::<dyn std::error::Error + 'static>(&self.source);
232 /// let backtrace = MyBacktrace::new();
233 /// let source = SourceError {};
234 /// let error = Error { source, backtrace };
235 /// let dyn_error = &error as &dyn std::error::Error;
236 /// let backtrace_ref = dyn_error.request_ref::<MyBacktrace>().unwrap();
238 /// assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
241 #[unstable(feature = "error_generic_member_access", issue = "99301")]
242 #[allow(unused_variables)]
243 fn provide<'a>(&'a self, req: &mut Demand<'a>) {}
247 #[unstable(feature = "error_generic_member_access", issue = "99301")]
248 impl<'b> Provider for dyn Error + 'b {
249 fn provide<'a>(&'a self, req: &mut Demand<'a>) {
255 // This is a hack to prevent `type_id` from being overridden by `Error`
256 // implementations, since that can enable unsound downcasting.
257 #[unstable(feature = "error_type_id", issue = "60784")]
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
265 /// Converts a type of [`Error`] into a box of dyn [`Error`].
270 /// use std::error::Error;
277 /// impl fmt::Display for AnError {
278 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 /// write!(f, "An error")
283 /// impl Error for AnError {}
285 /// let an_error = AnError;
286 /// assert!(0 == mem::size_of_val(&an_error));
287 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
288 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
290 fn from(err: E) -> Box<dyn Error + 'a> {
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
298 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
299 /// dyn [`Error`] + [`Send`] + [`Sync`].
304 /// use std::error::Error;
311 /// impl fmt::Display for AnError {
312 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 /// write!(f, "An error")
317 /// impl Error for AnError {}
319 /// unsafe impl Send for AnError {}
321 /// unsafe impl Sync for AnError {}
323 /// let an_error = AnError;
324 /// assert!(0 == mem::size_of_val(&an_error));
325 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
327 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
329 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
335 #[stable(feature = "rust1", since = "1.0.0")]
336 impl From<String> for Box<dyn Error + Send + Sync> {
337 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
342 /// use std::error::Error;
345 /// let a_string_error = "a string error".to_string();
346 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
348 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
351 fn from(err: String) -> Box<dyn Error + Send + Sync> {
352 struct StringError(String);
354 impl Error for StringError {
356 fn description(&self) -> &str {
361 impl Display for StringError {
362 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363 Display::fmt(&self.0, f)
367 // Purposefully skip printing "StringError(..)"
368 impl Debug for StringError {
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 Debug::fmt(&self.0, f)
374 Box::new(StringError(err))
379 #[stable(feature = "string_box_error", since = "1.6.0")]
380 impl From<String> for Box<dyn Error> {
381 /// Converts a [`String`] into a box of dyn [`Error`].
386 /// use std::error::Error;
389 /// let a_string_error = "a string error".to_string();
390 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
391 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
393 fn from(str_err: String) -> Box<dyn Error> {
394 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
395 let err2: Box<dyn Error> = err1;
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
403 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
405 /// [`str`]: prim@str
410 /// use std::error::Error;
413 /// let a_str_error = "a str error";
414 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
416 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
419 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
420 From::from(String::from(err))
425 #[stable(feature = "string_box_error", since = "1.6.0")]
426 impl From<&str> for Box<dyn Error> {
427 /// Converts a [`str`] into a box of dyn [`Error`].
429 /// [`str`]: prim@str
434 /// use std::error::Error;
437 /// let a_str_error = "a str error";
438 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
439 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
441 fn from(err: &str) -> Box<dyn Error> {
442 From::from(String::from(err))
447 #[stable(feature = "cow_box_error", since = "1.22.0")]
448 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
449 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
454 /// use std::error::Error;
456 /// use std::borrow::Cow;
458 /// let a_cow_str_error = Cow::from("a str error");
459 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
461 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
463 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
464 From::from(String::from(err))
469 #[stable(feature = "cow_box_error", since = "1.22.0")]
470 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
471 /// Converts a [`Cow`] into a box of dyn [`Error`].
476 /// use std::error::Error;
478 /// use std::borrow::Cow;
480 /// let a_cow_str_error = Cow::from("a str error");
481 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
482 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
484 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
485 From::from(String::from(err))
490 #[unstable(feature = "never_type", issue = "35121")]
495 feature = "allocator_api",
496 reason = "the precise API and guarantees it provides may be tweaked.",
499 impl Error for AllocError {}
502 #[stable(feature = "alloc_layout", since = "1.28.0")]
503 impl Error for LayoutError {}
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl Error for str::ParseBoolError {
509 fn description(&self) -> &str {
510 "failed to parse bool"
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl Error for str::Utf8Error {
518 fn description(&self) -> &str {
519 "invalid utf-8: corrupt contents"
524 #[stable(feature = "rust1", since = "1.0.0")]
525 impl Error for num::ParseIntError {
527 fn description(&self) -> &str {
533 #[stable(feature = "try_from", since = "1.34.0")]
534 impl Error for num::TryFromIntError {
536 fn description(&self) -> &str {
542 #[stable(feature = "try_from", since = "1.34.0")]
543 impl Error for array::TryFromSliceError {
545 fn description(&self) -> &str {
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl Error for num::ParseFloatError {
554 fn description(&self) -> &str {
560 #[stable(feature = "rust1", since = "1.0.0")]
561 impl Error for string::FromUtf8Error {
563 fn description(&self) -> &str {
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl Error for string::FromUtf16Error {
572 fn description(&self) -> &str {
578 #[stable(feature = "str_parse_error2", since = "1.8.0")]
579 impl Error for Infallible {
580 fn description(&self) -> &str {
586 #[stable(feature = "decode_utf16", since = "1.9.0")]
587 impl Error for char::DecodeUtf16Error {
589 fn description(&self) -> &str {
590 "unpaired surrogate found"
595 #[stable(feature = "u8_from_char", since = "1.59.0")]
596 impl Error for char::TryFromCharError {}
599 #[unstable(feature = "map_try_insert", issue = "82766")]
600 impl<'a, K: Debug + Ord, V: Debug> Error
601 for crate::collections::btree_map::OccupiedError<'a, K, V>
604 fn description(&self) -> &str {
610 #[unstable(feature = "map_try_insert", issue = "82766")]
611 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
613 fn description(&self) -> &str {
619 #[stable(feature = "box_error", since = "1.8.0")]
620 impl<T: Error> Error for Box<T> {
621 #[allow(deprecated, deprecated_in_future)]
622 fn description(&self) -> &str {
623 Error::description(&**self)
627 fn cause(&self) -> Option<&dyn Error> {
628 Error::cause(&**self)
631 fn source(&self) -> Option<&(dyn Error + 'static)> {
632 Error::source(&**self)
637 #[unstable(feature = "thin_box", issue = "92791")]
638 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
639 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
640 use core::ops::Deref;
641 self.deref().source()
646 #[stable(feature = "error_by_ref", since = "1.51.0")]
647 impl<'a, T: Error + ?Sized> Error for &'a T {
648 #[allow(deprecated, deprecated_in_future)]
649 fn description(&self) -> &str {
650 Error::description(&**self)
654 fn cause(&self) -> Option<&dyn Error> {
655 Error::cause(&**self)
658 fn source(&self) -> Option<&(dyn Error + 'static)> {
659 Error::source(&**self)
662 fn provide<'b>(&'b self, req: &mut Demand<'b>) {
663 Error::provide(&**self, req);
668 #[stable(feature = "arc_error", since = "1.52.0")]
669 impl<T: Error + ?Sized> Error for Arc<T> {
670 #[allow(deprecated, deprecated_in_future)]
671 fn description(&self) -> &str {
672 Error::description(&**self)
676 fn cause(&self) -> Option<&dyn Error> {
677 Error::cause(&**self)
680 fn source(&self) -> Option<&(dyn Error + 'static)> {
681 Error::source(&**self)
684 fn provide<'a>(&'a self, req: &mut Demand<'a>) {
685 Error::provide(&**self, req);
690 #[stable(feature = "fmt_error", since = "1.11.0")]
691 impl Error for fmt::Error {
693 fn description(&self) -> &str {
694 "an error occurred when formatting an argument"
699 #[stable(feature = "try_borrow", since = "1.13.0")]
700 impl Error for cell::BorrowError {
702 fn description(&self) -> &str {
703 "already mutably borrowed"
708 #[stable(feature = "try_borrow", since = "1.13.0")]
709 impl Error for cell::BorrowMutError {
711 fn description(&self) -> &str {
717 #[stable(feature = "try_from", since = "1.34.0")]
718 impl Error for char::CharTryFromError {
720 fn description(&self) -> &str {
721 "converted integer out of range for `char`"
726 #[stable(feature = "char_from_str", since = "1.20.0")]
727 impl Error for char::ParseCharError {
729 fn description(&self) -> &str {
735 #[stable(feature = "try_reserve", since = "1.57.0")]
736 impl Error for alloc::collections::TryReserveError {}
739 #[unstable(feature = "duration_checked_float", issue = "83400")]
740 impl Error for time::FromFloatSecsError {}
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl Error for alloc::ffi::NulError {
746 fn description(&self) -> &str {
747 "nul byte found in data"
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl From<alloc::ffi::NulError> for io::Error {
754 /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
755 fn from(_: alloc::ffi::NulError) -> io::Error {
756 io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
761 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
762 impl Error for core::ffi::FromBytesWithNulError {
764 fn description(&self) -> &str {
770 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
771 impl Error for core::ffi::FromBytesUntilNulError {}
774 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
775 impl Error for alloc::ffi::FromVecWithNulError {}
778 #[stable(feature = "cstring_into", since = "1.7.0")]
779 impl Error for alloc::ffi::IntoStringError {
781 fn description(&self) -> &str {
782 "C string contained non-utf8 bytes"
785 fn source(&self) -> Option<&(dyn Error + 'static)> {
786 Some(self.__source())
791 impl<'a> dyn Error + 'a {
792 /// Request a reference of type `T` as context about this error.
793 #[unstable(feature = "error_generic_member_access", issue = "99301")]
794 pub fn request_ref<T: ?Sized + 'static>(&'a self) -> Option<&'a T> {
795 core::any::request_ref(self)
798 /// Request a value of type `T` as context about this error.
799 #[unstable(feature = "error_generic_member_access", issue = "99301")]
800 pub fn request_value<T: 'static>(&'a self) -> Option<T> {
801 core::any::request_value(self)
805 // Copied from `any.rs`.
807 impl dyn Error + 'static {
808 /// Returns `true` if the inner type is the same as `T`.
809 #[stable(feature = "error_downcast", since = "1.3.0")]
811 pub fn is<T: Error + 'static>(&self) -> bool {
812 // Get `TypeId` of the type this function is instantiated with.
813 let t = TypeId::of::<T>();
815 // Get `TypeId` of the type in the trait object (`self`).
816 let concrete = self.type_id(private::Internal);
818 // Compare both `TypeId`s on equality.
822 /// Returns some reference to the inner value if it is of type `T`, or
823 /// `None` if it isn't.
824 #[stable(feature = "error_downcast", since = "1.3.0")]
826 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
828 unsafe { Some(&*(self as *const dyn Error as *const T)) }
834 /// Returns some mutable reference to the inner value if it is of type `T`, or
835 /// `None` if it isn't.
836 #[stable(feature = "error_downcast", since = "1.3.0")]
838 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
840 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
848 impl dyn Error + 'static + Send {
849 /// Forwards to the method defined on the type `dyn Error`.
850 #[stable(feature = "error_downcast", since = "1.3.0")]
852 pub fn is<T: Error + 'static>(&self) -> bool {
853 <dyn Error + 'static>::is::<T>(self)
856 /// Forwards to the method defined on the type `dyn Error`.
857 #[stable(feature = "error_downcast", since = "1.3.0")]
859 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
860 <dyn Error + 'static>::downcast_ref::<T>(self)
863 /// Forwards to the method defined on the type `dyn Error`.
864 #[stable(feature = "error_downcast", since = "1.3.0")]
866 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
867 <dyn Error + 'static>::downcast_mut::<T>(self)
870 /// Request a reference of type `T` as context about this error.
871 #[unstable(feature = "error_generic_member_access", issue = "99301")]
872 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
873 <dyn Error>::request_ref(self)
876 /// Request a value of type `T` as context about this error.
877 #[unstable(feature = "error_generic_member_access", issue = "99301")]
878 pub fn request_value<T: 'static>(&self) -> Option<T> {
879 <dyn Error>::request_value(self)
884 impl dyn Error + 'static + Send + Sync {
885 /// Forwards to the method defined on the type `dyn Error`.
886 #[stable(feature = "error_downcast", since = "1.3.0")]
888 pub fn is<T: Error + 'static>(&self) -> bool {
889 <dyn Error + 'static>::is::<T>(self)
892 /// Forwards to the method defined on the type `dyn Error`.
893 #[stable(feature = "error_downcast", since = "1.3.0")]
895 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
896 <dyn Error + 'static>::downcast_ref::<T>(self)
899 /// Forwards to the method defined on the type `dyn Error`.
900 #[stable(feature = "error_downcast", since = "1.3.0")]
902 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
903 <dyn Error + 'static>::downcast_mut::<T>(self)
906 /// Request a reference of type `T` as context about this error.
907 #[unstable(feature = "error_generic_member_access", issue = "99301")]
908 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
909 <dyn Error>::request_ref(self)
912 /// Request a value of type `T` as context about this error.
913 #[unstable(feature = "error_generic_member_access", issue = "99301")]
914 pub fn request_value<T: 'static>(&self) -> Option<T> {
915 <dyn Error>::request_value(self)
922 #[stable(feature = "error_downcast", since = "1.3.0")]
923 /// Attempts to downcast the box to a concrete type.
924 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
927 let raw: *mut dyn Error = Box::into_raw(self);
928 Ok(Box::from_raw(raw as *mut T))
935 /// Returns an iterator starting with the current error and continuing with
936 /// recursively calling [`Error::source`].
938 /// If you want to omit the current error and only use its sources,
944 /// #![feature(error_iter)]
945 /// use std::error::Error;
952 /// struct B(Option<Box<dyn Error + 'static>>);
954 /// impl fmt::Display for A {
955 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
960 /// impl fmt::Display for B {
961 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
966 /// impl Error for A {}
968 /// impl Error for B {
969 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
970 /// self.0.as_ref().map(|e| e.as_ref())
974 /// let b = B(Some(Box::new(A)));
976 /// // let err : Box<Error> = b.into(); // or
977 /// let err = &b as &(dyn Error);
979 /// let mut iter = err.sources();
981 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
982 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
983 /// assert!(iter.next().is_none());
984 /// assert!(iter.next().is_none());
986 #[unstable(feature = "error_iter", issue = "58520")]
988 pub fn sources(&self) -> Sources<'_> {
989 // You may think this method would be better in the Error trait, and you'd be right.
990 // Unfortunately that doesn't work, not because of the object safety rules but because we
991 // save a reference to self in Sources below as a trait object. If this method was
992 // declared in Error, then self would have the type &T where T is some concrete type which
993 // implements Error. We would need to coerce self to have type &dyn Error, but that requires
994 // that Self has a known size (i.e., Self: Sized). We can't put that bound on Error
995 // since that would forbid Error trait objects, and we can't put that bound on the method
996 // because that means the method can't be called on trait objects (we'd also need the
997 // 'static bound, but that isn't allowed because methods with bounds on Self other than
998 // Sized are not object-safe). Requiring an Unsize bound is not backwards compatible.
1000 // Two possible solutions are to start the iterator at self.source() instead of self (see
1001 // discussion on the tracking issue), or to wait for dyn* to exist (which would then permit
1004 Sources { current: Some(self) }
1008 /// An iterator over an [`Error`] and its sources.
1010 /// If you want to omit the initial error and only process
1011 /// its sources, use `skip(1)`.
1012 #[unstable(feature = "error_iter", issue = "58520")]
1013 #[derive(Clone, Debug)]
1015 pub struct Sources<'a> {
1016 current: Option<&'a (dyn Error + 'static)>,
1020 #[unstable(feature = "error_iter", issue = "58520")]
1021 impl<'a> Iterator for Sources<'a> {
1022 type Item = &'a (dyn Error + 'static);
1024 fn next(&mut self) -> Option<Self::Item> {
1025 let current = self.current;
1026 self.current = self.current.and_then(Error::source);
1032 impl dyn Error + Send {
1034 #[stable(feature = "error_downcast", since = "1.3.0")]
1035 /// Attempts to downcast the box to a concrete type.
1036 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
1037 let err: Box<dyn Error> = self;
1038 <dyn Error>::downcast(err).map_err(|s| unsafe {
1039 // Reapply the `Send` marker.
1040 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
1046 impl dyn Error + Send + Sync {
1048 #[stable(feature = "error_downcast", since = "1.3.0")]
1049 /// Attempts to downcast the box to a concrete type.
1050 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
1051 let err: Box<dyn Error> = self;
1052 <dyn Error>::downcast(err).map_err(|s| unsafe {
1053 // Reapply the `Send + Sync` marker.
1054 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
1059 /// An error reporter that prints an error and its sources.
1061 /// Report also exposes configuration options for formatting the error sources, either entirely on a
1062 /// single line, or in multi-line format with each source on a new line.
1064 /// `Report` only requires that the wrapped error implement `Error`. It doesn't require that the
1065 /// wrapped error be `Send`, `Sync`, or `'static`.
1070 /// #![feature(error_reporter)]
1071 /// use std::error::{Error, Report};
1074 /// #[derive(Debug)]
1075 /// struct SuperError {
1076 /// source: SuperErrorSideKick,
1079 /// impl fmt::Display for SuperError {
1080 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 /// write!(f, "SuperError is here!")
1085 /// impl Error for SuperError {
1086 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
1087 /// Some(&self.source)
1091 /// #[derive(Debug)]
1092 /// struct SuperErrorSideKick;
1094 /// impl fmt::Display for SuperErrorSideKick {
1095 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 /// write!(f, "SuperErrorSideKick is here!")
1100 /// impl Error for SuperErrorSideKick {}
1102 /// fn get_super_error() -> Result<(), SuperError> {
1103 /// Err(SuperError { source: SuperErrorSideKick })
1107 /// match get_super_error() {
1108 /// Err(e) => println!("Error: {}", Report::new(e)),
1109 /// _ => println!("No error"),
1114 /// This example produces the following output:
1117 /// Error: SuperError is here!: SuperErrorSideKick is here!
1120 /// ## Output consistency
1122 /// Report prints the same output via `Display` and `Debug`, so it works well with
1123 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
1126 /// #![feature(error_reporter)]
1127 /// use std::error::Report;
1128 /// # use std::error::Error;
1130 /// # #[derive(Debug)]
1131 /// # struct SuperError {
1132 /// # source: SuperErrorSideKick,
1134 /// # impl fmt::Display for SuperError {
1135 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1136 /// # write!(f, "SuperError is here!")
1139 /// # impl Error for SuperError {
1140 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1141 /// # Some(&self.source)
1144 /// # #[derive(Debug)]
1145 /// # struct SuperErrorSideKick;
1146 /// # impl fmt::Display for SuperErrorSideKick {
1147 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1148 /// # write!(f, "SuperErrorSideKick is here!")
1151 /// # impl Error for SuperErrorSideKick {}
1152 /// # fn get_super_error() -> Result<(), SuperError> {
1153 /// # Err(SuperError { source: SuperErrorSideKick })
1156 /// get_super_error().map_err(Report::new).unwrap();
1159 /// This example produces the following output:
1162 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
1163 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1166 /// ## Return from `main`
1168 /// `Report` also implements `From` for all types that implement [`Error`]; this when combined with
1169 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
1173 /// #![feature(error_reporter)]
1174 /// use std::error::Report;
1175 /// # use std::error::Error;
1177 /// # #[derive(Debug)]
1178 /// # struct SuperError {
1179 /// # source: SuperErrorSideKick,
1181 /// # impl fmt::Display for SuperError {
1182 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1183 /// # write!(f, "SuperError is here!")
1186 /// # impl Error for SuperError {
1187 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1188 /// # Some(&self.source)
1191 /// # #[derive(Debug)]
1192 /// # struct SuperErrorSideKick;
1193 /// # impl fmt::Display for SuperErrorSideKick {
1194 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1195 /// # write!(f, "SuperErrorSideKick is here!")
1198 /// # impl Error for SuperErrorSideKick {}
1199 /// # fn get_super_error() -> Result<(), SuperError> {
1200 /// # Err(SuperError { source: SuperErrorSideKick })
1203 /// fn main() -> Result<(), Report<SuperError>> {
1204 /// get_super_error()?;
1209 /// This example produces the following output:
1212 /// Error: SuperError is here!: SuperErrorSideKick is here!
1215 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1216 /// output format. If you want to make sure your `Report`s are pretty printed and include backtrace
1217 /// you will need to manually convert and enable those flags.
1220 /// #![feature(error_reporter)]
1221 /// use std::error::Report;
1222 /// # use std::error::Error;
1224 /// # #[derive(Debug)]
1225 /// # struct SuperError {
1226 /// # source: SuperErrorSideKick,
1228 /// # impl fmt::Display for SuperError {
1229 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1230 /// # write!(f, "SuperError is here!")
1233 /// # impl Error for SuperError {
1234 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1235 /// # Some(&self.source)
1238 /// # #[derive(Debug)]
1239 /// # struct SuperErrorSideKick;
1240 /// # impl fmt::Display for SuperErrorSideKick {
1241 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1242 /// # write!(f, "SuperErrorSideKick is here!")
1245 /// # impl Error for SuperErrorSideKick {}
1246 /// # fn get_super_error() -> Result<(), SuperError> {
1247 /// # Err(SuperError { source: SuperErrorSideKick })
1250 /// fn main() -> Result<(), Report<SuperError>> {
1251 /// get_super_error()
1252 /// .map_err(Report::from)
1253 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1258 /// This example produces the following output:
1261 /// Error: SuperError is here!
1264 /// SuperErrorSideKick is here!
1266 #[unstable(feature = "error_reporter", issue = "90172")]
1267 pub struct Report<E = Box<dyn Error>> {
1268 /// The error being reported.
1270 /// Whether a backtrace should be included as part of the report.
1271 show_backtrace: bool,
1272 /// Whether the report should be pretty-printed.
1280 /// Create a new `Report` from an input error.
1281 #[unstable(feature = "error_reporter", issue = "90172")]
1282 pub fn new(error: E) -> Report<E> {
1288 /// Enable pretty-printing the report across multiple lines.
1293 /// #![feature(error_reporter)]
1294 /// use std::error::Report;
1295 /// # use std::error::Error;
1297 /// # #[derive(Debug)]
1298 /// # struct SuperError {
1299 /// # source: SuperErrorSideKick,
1301 /// # impl fmt::Display for SuperError {
1302 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1303 /// # write!(f, "SuperError is here!")
1306 /// # impl Error for SuperError {
1307 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1308 /// # Some(&self.source)
1311 /// # #[derive(Debug)]
1312 /// # struct SuperErrorSideKick;
1313 /// # impl fmt::Display for SuperErrorSideKick {
1314 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1315 /// # write!(f, "SuperErrorSideKick is here!")
1318 /// # impl Error for SuperErrorSideKick {}
1320 /// let error = SuperError { source: SuperErrorSideKick };
1321 /// let report = Report::new(error).pretty(true);
1322 /// eprintln!("Error: {report:?}");
1325 /// This example produces the following output:
1328 /// Error: SuperError is here!
1331 /// SuperErrorSideKick is here!
1334 /// When there are multiple source errors the causes will be numbered in order of iteration
1335 /// starting from the outermost error.
1338 /// #![feature(error_reporter)]
1339 /// use std::error::Report;
1340 /// # use std::error::Error;
1342 /// # #[derive(Debug)]
1343 /// # struct SuperError {
1344 /// # source: SuperErrorSideKick,
1346 /// # impl fmt::Display for SuperError {
1347 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1348 /// # write!(f, "SuperError is here!")
1351 /// # impl Error for SuperError {
1352 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1353 /// # Some(&self.source)
1356 /// # #[derive(Debug)]
1357 /// # struct SuperErrorSideKick {
1358 /// # source: SuperErrorSideKickSideKick,
1360 /// # impl fmt::Display for SuperErrorSideKick {
1361 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1362 /// # write!(f, "SuperErrorSideKick is here!")
1365 /// # impl Error for SuperErrorSideKick {
1366 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1367 /// # Some(&self.source)
1370 /// # #[derive(Debug)]
1371 /// # struct SuperErrorSideKickSideKick;
1372 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1373 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1374 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1377 /// # impl Error for SuperErrorSideKickSideKick { }
1379 /// let source = SuperErrorSideKickSideKick;
1380 /// let source = SuperErrorSideKick { source };
1381 /// let error = SuperError { source };
1382 /// let report = Report::new(error).pretty(true);
1383 /// eprintln!("Error: {report:?}");
1386 /// This example produces the following output:
1389 /// Error: SuperError is here!
1392 /// 0: SuperErrorSideKick is here!
1393 /// 1: SuperErrorSideKickSideKick is here!
1395 #[unstable(feature = "error_reporter", issue = "90172")]
1396 pub fn pretty(mut self, pretty: bool) -> Self {
1397 self.pretty = pretty;
1401 /// Display backtrace if available when using pretty output format.
1405 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1406 /// outermost error. In this example it will display the backtrace from the second error in the
1407 /// sources, `SuperErrorSideKick`.
1410 /// #![feature(error_reporter)]
1411 /// #![feature(provide_any)]
1412 /// #![feature(error_generic_member_access)]
1413 /// # use std::error::Error;
1415 /// use std::any::Demand;
1416 /// use std::error::Report;
1417 /// use std::backtrace::Backtrace;
1419 /// # #[derive(Debug)]
1420 /// # struct SuperError {
1421 /// # source: SuperErrorSideKick,
1423 /// # impl fmt::Display for SuperError {
1424 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1425 /// # write!(f, "SuperError is here!")
1428 /// # impl Error for SuperError {
1429 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1430 /// # Some(&self.source)
1433 /// #[derive(Debug)]
1434 /// struct SuperErrorSideKick {
1435 /// backtrace: Backtrace,
1438 /// impl SuperErrorSideKick {
1439 /// fn new() -> SuperErrorSideKick {
1440 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1444 /// impl Error for SuperErrorSideKick {
1445 /// fn provide<'a>(&'a self, req: &mut Demand<'a>) {
1447 /// .provide_ref::<Backtrace>(&self.backtrace);
1451 /// // The rest of the example is unchanged ...
1452 /// # impl fmt::Display for SuperErrorSideKick {
1453 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1454 /// # write!(f, "SuperErrorSideKick is here!")
1458 /// let source = SuperErrorSideKick::new();
1459 /// let error = SuperError { source };
1460 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1461 /// eprintln!("Error: {report:?}");
1464 /// This example produces something similar to the following output:
1467 /// Error: SuperError is here!
1470 /// SuperErrorSideKick is here!
1472 /// Stack backtrace:
1473 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1474 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1475 /// 2: rust_out::main
1476 /// 3: core::ops::function::FnOnce::call_once
1477 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1478 /// 5: std::rt::lang_start::{{closure}}
1479 /// 6: std::panicking::try
1480 /// 7: std::rt::lang_start_internal
1481 /// 8: std::rt::lang_start
1483 /// 10: __libc_start_main
1486 #[unstable(feature = "error_reporter", issue = "90172")]
1487 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1488 self.show_backtrace = show_backtrace;
1497 fn backtrace(&self) -> Option<&Backtrace> {
1498 // have to grab the backtrace on the first error directly since that error may not be
1500 let backtrace = (&self.error as &dyn Error).request_ref();
1501 let backtrace = backtrace.or_else(|| {
1504 .map(|source| source.sources().find_map(|source| source.request_ref()))
1510 /// Format the report as a single line.
1511 #[unstable(feature = "error_reporter", issue = "90172")]
1512 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1513 write!(f, "{}", self.error)?;
1515 let sources = self.error.source().into_iter().flat_map(<dyn Error>::sources);
1517 for cause in sources {
1518 write!(f, ": {cause}")?;
1524 /// Format the report as multiple lines, with each error cause on its own line.
1525 #[unstable(feature = "error_reporter", issue = "90172")]
1526 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1527 let error = &self.error;
1529 write!(f, "{error}")?;
1531 if let Some(cause) = error.source() {
1532 write!(f, "\n\nCaused by:")?;
1534 let multiple = cause.source().is_some();
1536 for (ind, error) in cause.sources().enumerate() {
1538 let mut indented = Indented { inner: f };
1540 write!(indented, "{ind: >4}: {error}")?;
1542 write!(indented, " {error}")?;
1547 if self.show_backtrace {
1548 let backtrace = self.backtrace();
1550 if let Some(backtrace) = backtrace {
1551 let backtrace = backtrace.to_string();
1553 f.write_str("\n\nStack backtrace:\n")?;
1554 f.write_str(backtrace.trim_end())?;
1562 #[unstable(feature = "error_reporter", issue = "90172")]
1563 impl<E> From<E> for Report<E>
1567 fn from(error: E) -> Self {
1568 Report { error, show_backtrace: false, pretty: false }
1572 #[unstable(feature = "error_reporter", issue = "90172")]
1573 impl<E> fmt::Display for Report<E>
1577 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1578 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1582 // This type intentionally outputs the same format for `Display` and `Debug`for
1583 // situations where you unwrap a `Report` or return it from main.
1584 #[unstable(feature = "error_reporter", issue = "90172")]
1585 impl<E> fmt::Debug for Report<E>
1587 Report<E>: fmt::Display,
1589 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1590 fmt::Display::fmt(self, f)
1594 /// Wrapper type for indenting the inner source.
1595 struct Indented<'a, D> {
1599 impl<T> Write for Indented<'_, T>
1603 fn write_str(&mut self, s: &str) -> fmt::Result {
1604 for (i, line) in s.split('\n').enumerate() {
1606 self.inner.write_char('\n')?;
1607 self.inner.write_str(" ")?;
1610 self.inner.write_str(line)?;