1 #![doc = include_str!("../../core/src/error.md")]
2 #![stable(feature = "rust1", since = "1.0.0")]
10 use core::convert::Infallible;
13 use crate::alloc::{AllocError, LayoutError};
15 use crate::any::Demand;
17 use crate::any::{Provider, TypeId};
18 use crate::backtrace::Backtrace;
20 use crate::borrow::Cow;
26 use crate::fmt::Debug;
28 use crate::fmt::Display;
29 use crate::fmt::{self, Write};
33 use crate::mem::transmute;
45 #[cfg(not(bootstrap))]
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub use core::error::Error;
49 /// `Error` is a trait representing the basic expectations for error values,
50 /// i.e., values of type `E` in [`Result<T, E>`].
52 /// Errors must describe themselves through the [`Display`] and [`Debug`]
53 /// traits. Error messages are typically concise lowercase sentences without
54 /// trailing punctuation:
57 /// let err = "NaN".parse::<u32>().unwrap_err();
58 /// assert_eq!(err.to_string(), "invalid digit found in string");
61 /// Errors may provide cause information. [`Error::source()`] is generally
62 /// used when errors cross "abstraction boundaries". If one module must report
63 /// an error that is caused by an error from a lower-level module, it can allow
64 /// accessing that error via [`Error::source()`]. This makes it possible for the
65 /// high-level module to provide its own errors while also revealing some of the
66 /// implementation for debugging.
67 #[stable(feature = "rust1", since = "1.0.0")]
68 #[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
70 pub trait Error: Debug + Display {
71 /// The lower-level source of this error, if any.
76 /// use std::error::Error;
80 /// struct SuperError {
81 /// source: SuperErrorSideKick,
84 /// impl fmt::Display for SuperError {
85 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 /// write!(f, "SuperError is here!")
90 /// impl Error for SuperError {
91 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
92 /// Some(&self.source)
97 /// struct SuperErrorSideKick;
99 /// impl fmt::Display for SuperErrorSideKick {
100 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101 /// write!(f, "SuperErrorSideKick is here!")
105 /// impl Error for SuperErrorSideKick {}
107 /// fn get_super_error() -> Result<(), SuperError> {
108 /// Err(SuperError { source: SuperErrorSideKick })
112 /// match get_super_error() {
114 /// println!("Error: {e}");
115 /// println!("Caused by: {}", e.source().unwrap());
117 /// _ => println!("No error"),
121 #[stable(feature = "error_source", since = "1.30.0")]
122 fn source(&self) -> Option<&(dyn Error + 'static)> {
126 /// Gets the `TypeId` of `self`.
129 feature = "error_type_id",
130 reason = "this is memory-unsafe to override in user code",
133 fn type_id(&self, _: private::Internal) -> TypeId
141 /// if let Err(e) = "xc".parse::<u32>() {
142 /// // Print `e` itself, no need for description().
143 /// eprintln!("Error: {e}");
146 #[stable(feature = "rust1", since = "1.0.0")]
147 #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")]
148 fn description(&self) -> &str {
149 "description() is deprecated; use Display"
152 #[stable(feature = "rust1", since = "1.0.0")]
155 note = "replaced by Error::source, which can support downcasting"
157 #[allow(missing_docs)]
158 fn cause(&self) -> Option<&dyn Error> {
162 /// Provides type based access to context intended for error reports.
164 /// Used in conjunction with [`Demand::provide_value`] and [`Demand::provide_ref`] to extract
165 /// references to member variables from `dyn Error` trait objects.
170 /// #![feature(provide_any)]
171 /// #![feature(error_generic_member_access)]
173 /// use core::any::Demand;
176 /// struct MyBacktrace {
180 /// impl MyBacktrace {
181 /// fn new() -> MyBacktrace {
188 /// struct SourceError {
192 /// impl fmt::Display for SourceError {
193 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 /// write!(f, "Example Source Error")
198 /// impl std::error::Error for SourceError {}
202 /// source: SourceError,
203 /// backtrace: MyBacktrace,
206 /// impl fmt::Display for Error {
207 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 /// write!(f, "Example Error")
212 /// impl std::error::Error for Error {
213 /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
215 /// .provide_ref::<MyBacktrace>(&self.backtrace)
216 /// .provide_ref::<dyn std::error::Error + 'static>(&self.source);
221 /// let backtrace = MyBacktrace::new();
222 /// let source = SourceError {};
223 /// let error = Error { source, backtrace };
224 /// let dyn_error = &error as &dyn std::error::Error;
225 /// let backtrace_ref = dyn_error.request_ref::<MyBacktrace>().unwrap();
227 /// assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
230 #[unstable(feature = "error_generic_member_access", issue = "99301")]
231 #[allow(unused_variables)]
232 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {}
236 #[unstable(feature = "error_generic_member_access", issue = "99301")]
237 impl<'b> Provider for dyn Error + 'b {
238 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
244 // This is a hack to prevent `type_id` from being overridden by `Error`
245 // implementations, since that can enable unsound downcasting.
246 #[unstable(feature = "error_type_id", issue = "60784")]
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
254 /// Converts a type of [`Error`] into a box of dyn [`Error`].
259 /// use std::error::Error;
266 /// impl fmt::Display for AnError {
267 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 /// write!(f, "An error")
272 /// impl Error for AnError {}
274 /// let an_error = AnError;
275 /// assert!(0 == mem::size_of_val(&an_error));
276 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
277 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
279 fn from(err: E) -> Box<dyn Error + 'a> {
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
287 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
288 /// dyn [`Error`] + [`Send`] + [`Sync`].
293 /// use std::error::Error;
300 /// impl fmt::Display for AnError {
301 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 /// write!(f, "An error")
306 /// impl Error for AnError {}
308 /// unsafe impl Send for AnError {}
310 /// unsafe impl Sync for AnError {}
312 /// let an_error = AnError;
313 /// assert!(0 == mem::size_of_val(&an_error));
314 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
316 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
318 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl From<String> for Box<dyn Error + Send + Sync> {
326 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
331 /// use std::error::Error;
334 /// let a_string_error = "a string error".to_string();
335 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
337 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
340 fn from(err: String) -> Box<dyn Error + Send + Sync> {
341 struct StringError(String);
343 impl Error for StringError {
345 fn description(&self) -> &str {
350 impl Display for StringError {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 Display::fmt(&self.0, f)
356 // Purposefully skip printing "StringError(..)"
357 impl Debug for StringError {
358 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359 Debug::fmt(&self.0, f)
363 Box::new(StringError(err))
368 #[stable(feature = "string_box_error", since = "1.6.0")]
369 impl From<String> for Box<dyn Error> {
370 /// Converts a [`String`] into a box of dyn [`Error`].
375 /// use std::error::Error;
378 /// let a_string_error = "a string error".to_string();
379 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
380 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
382 fn from(str_err: String) -> Box<dyn Error> {
383 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
384 let err2: Box<dyn Error> = err1;
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
392 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
394 /// [`str`]: prim@str
399 /// use std::error::Error;
402 /// let a_str_error = "a str error";
403 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
405 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
408 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
409 From::from(String::from(err))
414 #[stable(feature = "string_box_error", since = "1.6.0")]
415 impl From<&str> for Box<dyn Error> {
416 /// Converts a [`str`] into a box of dyn [`Error`].
418 /// [`str`]: prim@str
423 /// use std::error::Error;
426 /// let a_str_error = "a str error";
427 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
428 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
430 fn from(err: &str) -> Box<dyn Error> {
431 From::from(String::from(err))
436 #[stable(feature = "cow_box_error", since = "1.22.0")]
437 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
438 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
443 /// use std::error::Error;
445 /// use std::borrow::Cow;
447 /// let a_cow_str_error = Cow::from("a str error");
448 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
450 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
452 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
453 From::from(String::from(err))
458 #[stable(feature = "cow_box_error", since = "1.22.0")]
459 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
460 /// Converts a [`Cow`] into a box of dyn [`Error`].
465 /// use std::error::Error;
467 /// use std::borrow::Cow;
469 /// let a_cow_str_error = Cow::from("a str error");
470 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
471 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
473 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
474 From::from(String::from(err))
479 #[unstable(feature = "never_type", issue = "35121")]
484 feature = "allocator_api",
485 reason = "the precise API and guarantees it provides may be tweaked.",
488 impl Error for AllocError {}
491 #[stable(feature = "alloc_layout", since = "1.28.0")]
492 impl Error for LayoutError {}
495 #[stable(feature = "rust1", since = "1.0.0")]
496 impl Error for str::ParseBoolError {
498 fn description(&self) -> &str {
499 "failed to parse bool"
504 #[stable(feature = "rust1", since = "1.0.0")]
505 impl Error for str::Utf8Error {
507 fn description(&self) -> &str {
508 "invalid utf-8: corrupt contents"
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl Error for num::ParseIntError {
516 fn description(&self) -> &str {
522 #[stable(feature = "try_from", since = "1.34.0")]
523 impl Error for num::TryFromIntError {
525 fn description(&self) -> &str {
531 #[stable(feature = "try_from", since = "1.34.0")]
532 impl Error for array::TryFromSliceError {
534 fn description(&self) -> &str {
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl Error for num::ParseFloatError {
543 fn description(&self) -> &str {
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl Error for string::FromUtf8Error {
552 fn description(&self) -> &str {
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl Error for string::FromUtf16Error {
561 fn description(&self) -> &str {
567 #[stable(feature = "str_parse_error2", since = "1.8.0")]
568 impl Error for Infallible {
569 fn description(&self) -> &str {
575 #[stable(feature = "decode_utf16", since = "1.9.0")]
576 impl Error for char::DecodeUtf16Error {
578 fn description(&self) -> &str {
579 "unpaired surrogate found"
584 #[stable(feature = "u8_from_char", since = "1.59.0")]
585 impl Error for char::TryFromCharError {}
588 #[unstable(feature = "map_try_insert", issue = "82766")]
589 impl<'a, K: Debug + Ord, V: Debug> Error
590 for crate::collections::btree_map::OccupiedError<'a, K, V>
593 fn description(&self) -> &str {
599 #[unstable(feature = "map_try_insert", issue = "82766")]
600 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
602 fn description(&self) -> &str {
608 #[stable(feature = "box_error", since = "1.8.0")]
609 impl<T: Error> Error for Box<T> {
610 #[allow(deprecated, deprecated_in_future)]
611 fn description(&self) -> &str {
612 Error::description(&**self)
616 fn cause(&self) -> Option<&dyn Error> {
617 Error::cause(&**self)
620 fn source(&self) -> Option<&(dyn Error + 'static)> {
621 Error::source(&**self)
626 #[unstable(feature = "thin_box", issue = "92791")]
627 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
628 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
629 use core::ops::Deref;
630 self.deref().source()
635 #[stable(feature = "error_by_ref", since = "1.51.0")]
636 impl<'a, T: Error + ?Sized> Error for &'a T {
637 #[allow(deprecated, deprecated_in_future)]
638 fn description(&self) -> &str {
639 Error::description(&**self)
643 fn cause(&self) -> Option<&dyn Error> {
644 Error::cause(&**self)
647 fn source(&self) -> Option<&(dyn Error + 'static)> {
648 Error::source(&**self)
651 fn provide<'b>(&'b self, demand: &mut Demand<'b>) {
652 Error::provide(&**self, demand);
657 #[stable(feature = "arc_error", since = "1.52.0")]
658 impl<T: Error + ?Sized> Error for Arc<T> {
659 #[allow(deprecated, deprecated_in_future)]
660 fn description(&self) -> &str {
661 Error::description(&**self)
665 fn cause(&self) -> Option<&dyn Error> {
666 Error::cause(&**self)
669 fn source(&self) -> Option<&(dyn Error + 'static)> {
670 Error::source(&**self)
673 fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
674 Error::provide(&**self, demand);
679 #[stable(feature = "fmt_error", since = "1.11.0")]
680 impl Error for fmt::Error {
682 fn description(&self) -> &str {
683 "an error occurred when formatting an argument"
688 #[stable(feature = "try_borrow", since = "1.13.0")]
689 impl Error for cell::BorrowError {
691 fn description(&self) -> &str {
692 "already mutably borrowed"
697 #[stable(feature = "try_borrow", since = "1.13.0")]
698 impl Error for cell::BorrowMutError {
700 fn description(&self) -> &str {
706 #[stable(feature = "try_from", since = "1.34.0")]
707 impl Error for char::CharTryFromError {
709 fn description(&self) -> &str {
710 "converted integer out of range for `char`"
715 #[stable(feature = "char_from_str", since = "1.20.0")]
716 impl Error for char::ParseCharError {
718 fn description(&self) -> &str {
724 #[stable(feature = "try_reserve", since = "1.57.0")]
725 impl Error for alloc::collections::TryReserveError {}
728 #[unstable(feature = "duration_checked_float", issue = "83400")]
729 impl Error for time::FromFloatSecsError {}
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl Error for alloc::ffi::NulError {
735 fn description(&self) -> &str {
736 "nul byte found in data"
741 #[stable(feature = "rust1", since = "1.0.0")]
742 impl From<alloc::ffi::NulError> for io::Error {
743 /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
744 fn from(_: alloc::ffi::NulError) -> io::Error {
745 io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
750 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
751 impl Error for core::ffi::FromBytesWithNulError {
753 fn description(&self) -> &str {
759 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
760 impl Error for core::ffi::FromBytesUntilNulError {}
763 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
764 impl Error for alloc::ffi::FromVecWithNulError {}
767 #[stable(feature = "cstring_into", since = "1.7.0")]
768 impl Error for alloc::ffi::IntoStringError {
770 fn description(&self) -> &str {
771 "C string contained non-utf8 bytes"
774 fn source(&self) -> Option<&(dyn Error + 'static)> {
775 Some(self.__source())
780 impl<'a> dyn Error + 'a {
781 /// Request a reference of type `T` as context about this error.
782 #[unstable(feature = "error_generic_member_access", issue = "99301")]
783 pub fn request_ref<T: ?Sized + 'static>(&'a self) -> Option<&'a T> {
784 core::any::request_ref(self)
787 /// Request a value of type `T` as context about this error.
788 #[unstable(feature = "error_generic_member_access", issue = "99301")]
789 pub fn request_value<T: 'static>(&'a self) -> Option<T> {
790 core::any::request_value(self)
794 // 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)) }
837 impl dyn Error + 'static + Send {
838 /// Forwards to the method defined on the type `dyn Error`.
839 #[stable(feature = "error_downcast", since = "1.3.0")]
841 pub fn is<T: Error + 'static>(&self) -> bool {
842 <dyn Error + 'static>::is::<T>(self)
845 /// Forwards to the method defined on the type `dyn Error`.
846 #[stable(feature = "error_downcast", since = "1.3.0")]
848 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
849 <dyn Error + 'static>::downcast_ref::<T>(self)
852 /// Forwards to the method defined on the type `dyn Error`.
853 #[stable(feature = "error_downcast", since = "1.3.0")]
855 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
856 <dyn Error + 'static>::downcast_mut::<T>(self)
859 /// Request a reference of type `T` as context about this error.
860 #[unstable(feature = "error_generic_member_access", issue = "99301")]
861 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
862 <dyn Error>::request_ref(self)
865 /// Request a value of type `T` as context about this error.
866 #[unstable(feature = "error_generic_member_access", issue = "99301")]
867 pub fn request_value<T: 'static>(&self) -> Option<T> {
868 <dyn Error>::request_value(self)
873 impl dyn Error + 'static + Send + Sync {
874 /// Forwards to the method defined on the type `dyn Error`.
875 #[stable(feature = "error_downcast", since = "1.3.0")]
877 pub fn is<T: Error + 'static>(&self) -> bool {
878 <dyn Error + 'static>::is::<T>(self)
881 /// Forwards to the method defined on the type `dyn Error`.
882 #[stable(feature = "error_downcast", since = "1.3.0")]
884 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
885 <dyn Error + 'static>::downcast_ref::<T>(self)
888 /// Forwards to the method defined on the type `dyn Error`.
889 #[stable(feature = "error_downcast", since = "1.3.0")]
891 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
892 <dyn Error + 'static>::downcast_mut::<T>(self)
895 /// Request a reference of type `T` as context about this error.
896 #[unstable(feature = "error_generic_member_access", issue = "99301")]
897 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
898 <dyn Error>::request_ref(self)
901 /// Request a value of type `T` as context about this error.
902 #[unstable(feature = "error_generic_member_access", issue = "99301")]
903 pub fn request_value<T: 'static>(&self) -> Option<T> {
904 <dyn Error>::request_value(self)
911 #[stable(feature = "error_downcast", since = "1.3.0")]
912 /// Attempts to downcast the box to a concrete type.
913 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
916 let raw: *mut dyn Error = Box::into_raw(self);
917 Ok(Box::from_raw(raw as *mut T))
924 /// Returns an iterator starting with the current error and continuing with
925 /// recursively calling [`Error::source`].
927 /// If you want to omit the current error and only use its sources,
933 /// #![feature(error_iter)]
934 /// use std::error::Error;
941 /// struct B(Option<Box<dyn Error + 'static>>);
943 /// impl fmt::Display for A {
944 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949 /// impl fmt::Display for B {
950 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955 /// impl Error for A {}
957 /// impl Error for B {
958 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
959 /// self.0.as_ref().map(|e| e.as_ref())
963 /// let b = B(Some(Box::new(A)));
965 /// // let err : Box<Error> = b.into(); // or
966 /// let err = &b as &(dyn Error);
968 /// let mut iter = err.sources();
970 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
971 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
972 /// assert!(iter.next().is_none());
973 /// assert!(iter.next().is_none());
975 #[unstable(feature = "error_iter", issue = "58520")]
977 pub fn sources(&self) -> Sources<'_> {
978 // You may think this method would be better in the Error trait, and you'd be right.
979 // Unfortunately that doesn't work, not because of the object safety rules but because we
980 // save a reference to self in Sources below as a trait object. If this method was
981 // declared in Error, then self would have the type &T where T is some concrete type which
982 // implements Error. We would need to coerce self to have type &dyn Error, but that requires
983 // that Self has a known size (i.e., Self: Sized). We can't put that bound on Error
984 // since that would forbid Error trait objects, and we can't put that bound on the method
985 // because that means the method can't be called on trait objects (we'd also need the
986 // 'static bound, but that isn't allowed because methods with bounds on Self other than
987 // Sized are not object-safe). Requiring an Unsize bound is not backwards compatible.
989 Sources { current: Some(self) }
993 /// An iterator over an [`Error`] and its sources.
995 /// If you want to omit the initial error and only process
996 /// its sources, use `skip(1)`.
997 #[unstable(feature = "error_iter", issue = "58520")]
998 #[derive(Clone, Debug)]
1000 pub struct Sources<'a> {
1001 current: Option<&'a (dyn Error + 'static)>,
1005 #[unstable(feature = "error_iter", issue = "58520")]
1006 impl<'a> Iterator for Sources<'a> {
1007 type Item = &'a (dyn Error + 'static);
1009 fn next(&mut self) -> Option<Self::Item> {
1010 let current = self.current;
1011 self.current = self.current.and_then(Error::source);
1017 impl dyn Error + Send {
1019 #[stable(feature = "error_downcast", since = "1.3.0")]
1020 /// Attempts to downcast the box to a concrete type.
1021 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
1022 let err: Box<dyn Error> = self;
1023 <dyn Error>::downcast(err).map_err(|s| unsafe {
1024 // Reapply the `Send` marker.
1025 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
1031 impl dyn Error + Send + Sync {
1033 #[stable(feature = "error_downcast", since = "1.3.0")]
1034 /// Attempts to downcast the box to a concrete type.
1035 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
1036 let err: Box<dyn Error> = self;
1037 <dyn Error>::downcast(err).map_err(|s| unsafe {
1038 // Reapply the `Send + Sync` marker.
1039 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
1044 /// An error reporter that prints an error and its sources.
1046 /// Report also exposes configuration options for formatting the error sources, either entirely on a
1047 /// single line, or in multi-line format with each source on a new line.
1049 /// `Report` only requires that the wrapped error implement `Error`. It doesn't require that the
1050 /// wrapped error be `Send`, `Sync`, or `'static`.
1055 /// #![feature(error_reporter)]
1056 /// use std::error::{Error, Report};
1059 /// #[derive(Debug)]
1060 /// struct SuperError {
1061 /// source: SuperErrorSideKick,
1064 /// impl fmt::Display for SuperError {
1065 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1066 /// write!(f, "SuperError is here!")
1070 /// impl Error for SuperError {
1071 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
1072 /// Some(&self.source)
1076 /// #[derive(Debug)]
1077 /// struct SuperErrorSideKick;
1079 /// impl fmt::Display for SuperErrorSideKick {
1080 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1081 /// write!(f, "SuperErrorSideKick is here!")
1085 /// impl Error for SuperErrorSideKick {}
1087 /// fn get_super_error() -> Result<(), SuperError> {
1088 /// Err(SuperError { source: SuperErrorSideKick })
1092 /// match get_super_error() {
1093 /// Err(e) => println!("Error: {}", Report::new(e)),
1094 /// _ => println!("No error"),
1099 /// This example produces the following output:
1102 /// Error: SuperError is here!: SuperErrorSideKick is here!
1105 /// ## Output consistency
1107 /// Report prints the same output via `Display` and `Debug`, so it works well with
1108 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
1111 /// #![feature(error_reporter)]
1112 /// use std::error::Report;
1113 /// # use std::error::Error;
1115 /// # #[derive(Debug)]
1116 /// # struct SuperError {
1117 /// # source: SuperErrorSideKick,
1119 /// # impl fmt::Display for SuperError {
1120 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 /// # write!(f, "SuperError is here!")
1124 /// # impl Error for SuperError {
1125 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1126 /// # Some(&self.source)
1129 /// # #[derive(Debug)]
1130 /// # struct SuperErrorSideKick;
1131 /// # impl fmt::Display for SuperErrorSideKick {
1132 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1133 /// # write!(f, "SuperErrorSideKick is here!")
1136 /// # impl Error for SuperErrorSideKick {}
1137 /// # fn get_super_error() -> Result<(), SuperError> {
1138 /// # Err(SuperError { source: SuperErrorSideKick })
1141 /// get_super_error().map_err(Report::new).unwrap();
1144 /// This example produces the following output:
1147 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
1148 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
1151 /// ## Return from `main`
1153 /// `Report` also implements `From` for all types that implement [`Error`]; this when combined with
1154 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
1158 /// #![feature(error_reporter)]
1159 /// use std::error::Report;
1160 /// # use std::error::Error;
1162 /// # #[derive(Debug)]
1163 /// # struct SuperError {
1164 /// # source: SuperErrorSideKick,
1166 /// # impl fmt::Display for SuperError {
1167 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 /// # write!(f, "SuperError is here!")
1171 /// # impl Error for SuperError {
1172 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1173 /// # Some(&self.source)
1176 /// # #[derive(Debug)]
1177 /// # struct SuperErrorSideKick;
1178 /// # impl fmt::Display for SuperErrorSideKick {
1179 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180 /// # write!(f, "SuperErrorSideKick is here!")
1183 /// # impl Error for SuperErrorSideKick {}
1184 /// # fn get_super_error() -> Result<(), SuperError> {
1185 /// # Err(SuperError { source: SuperErrorSideKick })
1188 /// fn main() -> Result<(), Report<SuperError>> {
1189 /// get_super_error()?;
1194 /// This example produces the following output:
1197 /// Error: SuperError is here!: SuperErrorSideKick is here!
1200 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1201 /// output format. If you want to make sure your `Report`s are pretty printed and include backtrace
1202 /// you will need to manually convert and enable those flags.
1205 /// #![feature(error_reporter)]
1206 /// use std::error::Report;
1207 /// # use std::error::Error;
1209 /// # #[derive(Debug)]
1210 /// # struct SuperError {
1211 /// # source: SuperErrorSideKick,
1213 /// # impl fmt::Display for SuperError {
1214 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215 /// # write!(f, "SuperError is here!")
1218 /// # impl Error for SuperError {
1219 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1220 /// # Some(&self.source)
1223 /// # #[derive(Debug)]
1224 /// # struct SuperErrorSideKick;
1225 /// # impl fmt::Display for SuperErrorSideKick {
1226 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 /// # write!(f, "SuperErrorSideKick is here!")
1230 /// # impl Error for SuperErrorSideKick {}
1231 /// # fn get_super_error() -> Result<(), SuperError> {
1232 /// # Err(SuperError { source: SuperErrorSideKick })
1235 /// fn main() -> Result<(), Report<SuperError>> {
1236 /// get_super_error()
1237 /// .map_err(Report::from)
1238 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1243 /// This example produces the following output:
1246 /// Error: SuperError is here!
1249 /// SuperErrorSideKick is here!
1251 #[unstable(feature = "error_reporter", issue = "90172")]
1252 pub struct Report<E = Box<dyn Error>> {
1253 /// The error being reported.
1255 /// Whether a backtrace should be included as part of the report.
1256 show_backtrace: bool,
1257 /// Whether the report should be pretty-printed.
1265 /// Create a new `Report` from an input error.
1266 #[unstable(feature = "error_reporter", issue = "90172")]
1267 pub fn new(error: E) -> Report<E> {
1273 /// Enable pretty-printing the report across multiple lines.
1278 /// #![feature(error_reporter)]
1279 /// use std::error::Report;
1280 /// # use std::error::Error;
1282 /// # #[derive(Debug)]
1283 /// # struct SuperError {
1284 /// # source: SuperErrorSideKick,
1286 /// # impl fmt::Display for SuperError {
1287 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1288 /// # write!(f, "SuperError is here!")
1291 /// # impl Error for SuperError {
1292 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1293 /// # Some(&self.source)
1296 /// # #[derive(Debug)]
1297 /// # struct SuperErrorSideKick;
1298 /// # impl fmt::Display for SuperErrorSideKick {
1299 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1300 /// # write!(f, "SuperErrorSideKick is here!")
1303 /// # impl Error for SuperErrorSideKick {}
1305 /// let error = SuperError { source: SuperErrorSideKick };
1306 /// let report = Report::new(error).pretty(true);
1307 /// eprintln!("Error: {report:?}");
1310 /// This example produces the following output:
1313 /// Error: SuperError is here!
1316 /// SuperErrorSideKick is here!
1319 /// When there are multiple source errors the causes will be numbered in order of iteration
1320 /// starting from the outermost error.
1323 /// #![feature(error_reporter)]
1324 /// use std::error::Report;
1325 /// # use std::error::Error;
1327 /// # #[derive(Debug)]
1328 /// # struct SuperError {
1329 /// # source: SuperErrorSideKick,
1331 /// # impl fmt::Display for SuperError {
1332 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333 /// # write!(f, "SuperError is here!")
1336 /// # impl Error for SuperError {
1337 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1338 /// # Some(&self.source)
1341 /// # #[derive(Debug)]
1342 /// # struct SuperErrorSideKick {
1343 /// # source: SuperErrorSideKickSideKick,
1345 /// # impl fmt::Display for SuperErrorSideKick {
1346 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1347 /// # write!(f, "SuperErrorSideKick is here!")
1350 /// # impl Error for SuperErrorSideKick {
1351 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1352 /// # Some(&self.source)
1355 /// # #[derive(Debug)]
1356 /// # struct SuperErrorSideKickSideKick;
1357 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1358 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1359 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1362 /// # impl Error for SuperErrorSideKickSideKick { }
1364 /// let source = SuperErrorSideKickSideKick;
1365 /// let source = SuperErrorSideKick { source };
1366 /// let error = SuperError { source };
1367 /// let report = Report::new(error).pretty(true);
1368 /// eprintln!("Error: {report:?}");
1371 /// This example produces the following output:
1374 /// Error: SuperError is here!
1377 /// 0: SuperErrorSideKick is here!
1378 /// 1: SuperErrorSideKickSideKick is here!
1380 #[unstable(feature = "error_reporter", issue = "90172")]
1381 pub fn pretty(mut self, pretty: bool) -> Self {
1382 self.pretty = pretty;
1386 /// Display backtrace if available when using pretty output format.
1390 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1391 /// outermost error. In this example it will display the backtrace from the second error in the
1392 /// sources, `SuperErrorSideKick`.
1395 /// #![feature(error_reporter)]
1396 /// #![feature(provide_any)]
1397 /// #![feature(error_generic_member_access)]
1398 /// # use std::error::Error;
1400 /// use std::any::Demand;
1401 /// use std::error::Report;
1402 /// use std::backtrace::Backtrace;
1404 /// # #[derive(Debug)]
1405 /// # struct SuperError {
1406 /// # source: SuperErrorSideKick,
1408 /// # impl fmt::Display for SuperError {
1409 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1410 /// # write!(f, "SuperError is here!")
1413 /// # impl Error for SuperError {
1414 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1415 /// # Some(&self.source)
1418 /// #[derive(Debug)]
1419 /// struct SuperErrorSideKick {
1420 /// backtrace: Backtrace,
1423 /// impl SuperErrorSideKick {
1424 /// fn new() -> SuperErrorSideKick {
1425 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1429 /// impl Error for SuperErrorSideKick {
1430 /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
1431 /// demand.provide_ref::<Backtrace>(&self.backtrace);
1435 /// // The rest of the example is unchanged ...
1436 /// # impl fmt::Display for SuperErrorSideKick {
1437 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1438 /// # write!(f, "SuperErrorSideKick is here!")
1442 /// let source = SuperErrorSideKick::new();
1443 /// let error = SuperError { source };
1444 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1445 /// eprintln!("Error: {report:?}");
1448 /// This example produces something similar to the following output:
1451 /// Error: SuperError is here!
1454 /// SuperErrorSideKick is here!
1456 /// Stack backtrace:
1457 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1458 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1459 /// 2: rust_out::main
1460 /// 3: core::ops::function::FnOnce::call_once
1461 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1462 /// 5: std::rt::lang_start::{{closure}}
1463 /// 6: std::panicking::try
1464 /// 7: std::rt::lang_start_internal
1465 /// 8: std::rt::lang_start
1467 /// 10: __libc_start_main
1470 #[unstable(feature = "error_reporter", issue = "90172")]
1471 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1472 self.show_backtrace = show_backtrace;
1481 fn backtrace(&self) -> Option<&Backtrace> {
1482 // have to grab the backtrace on the first error directly since that error may not be
1484 let backtrace = (&self.error as &dyn Error).request_ref();
1485 let backtrace = backtrace.or_else(|| {
1488 .map(|source| source.sources().find_map(|source| source.request_ref()))
1494 /// Format the report as a single line.
1495 #[unstable(feature = "error_reporter", issue = "90172")]
1496 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1497 write!(f, "{}", self.error)?;
1499 let sources = self.error.source().into_iter().flat_map(<dyn Error>::sources);
1501 for cause in sources {
1502 write!(f, ": {cause}")?;
1508 /// Format the report as multiple lines, with each error cause on its own line.
1509 #[unstable(feature = "error_reporter", issue = "90172")]
1510 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1511 let error = &self.error;
1513 write!(f, "{error}")?;
1515 if let Some(cause) = error.source() {
1516 write!(f, "\n\nCaused by:")?;
1518 let multiple = cause.source().is_some();
1520 for (ind, error) in cause.sources().enumerate() {
1522 let mut indented = Indented { inner: f };
1524 write!(indented, "{ind: >4}: {error}")?;
1526 write!(indented, " {error}")?;
1531 if self.show_backtrace {
1532 let backtrace = self.backtrace();
1534 if let Some(backtrace) = backtrace {
1535 let backtrace = backtrace.to_string();
1537 f.write_str("\n\nStack backtrace:\n")?;
1538 f.write_str(backtrace.trim_end())?;
1546 #[unstable(feature = "error_reporter", issue = "90172")]
1547 impl<E> From<E> for Report<E>
1551 fn from(error: E) -> Self {
1552 Report { error, show_backtrace: false, pretty: false }
1556 #[unstable(feature = "error_reporter", issue = "90172")]
1557 impl<E> fmt::Display for Report<E>
1561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1562 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1566 // This type intentionally outputs the same format for `Display` and `Debug`for
1567 // situations where you unwrap a `Report` or return it from main.
1568 #[unstable(feature = "error_reporter", issue = "90172")]
1569 impl<E> fmt::Debug for Report<E>
1571 Report<E>: fmt::Display,
1573 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1574 fmt::Display::fmt(self, f)
1578 /// Wrapper type for indenting the inner source.
1579 struct Indented<'a, D> {
1583 impl<T> Write for Indented<'_, T>
1587 fn write_str(&mut self, s: &str) -> fmt::Result {
1588 for (i, line) in s.split('\n').enumerate() {
1590 self.inner.write_char('\n')?;
1591 self.inner.write_str(" ")?;
1594 self.inner.write_str(line)?;