1 //! Traits for working with Errors.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 // A note about crates and the facade:
7 // Originally, the `Error` trait was defined in libcore, and the impls
8 // were scattered about. However, coherence objected to this
9 // arrangement, because to create the blanket impls for `Box` required
10 // knowing that `&str: !Error`, and we have no means to deal with that
11 // sort of conflict just now. Therefore, for the time being, we have
12 // moved the `Error` trait into libstd. As we evolve a sol'n to the
13 // coherence challenge (e.g., specialization, neg impls, etc) we can
14 // reconsider what crate these items belong in.
20 use core::convert::Infallible;
22 use crate::alloc::{AllocError, LayoutError};
23 use crate::any::TypeId;
24 use crate::backtrace::Backtrace;
25 use crate::borrow::Cow;
28 use crate::fmt::{self, Debug, Display, Write};
30 use crate::mem::transmute;
37 /// `Error` is a trait representing the basic expectations for error values,
38 /// i.e., values of type `E` in [`Result<T, E>`].
40 /// Errors must describe themselves through the [`Display`] and [`Debug`]
41 /// traits. Error messages are typically concise lowercase sentences without
42 /// trailing punctuation:
45 /// let err = "NaN".parse::<u32>().unwrap_err();
46 /// assert_eq!(err.to_string(), "invalid digit found in string");
49 /// Errors may provide cause chain information. [`Error::source()`] is generally
50 /// used when errors cross "abstraction boundaries". If one module must report
51 /// an error that is caused by an error from a lower-level module, it can allow
52 /// accessing that error via [`Error::source()`]. This makes it possible for the
53 /// high-level module to provide its own errors while also revealing some of the
54 /// implementation for debugging via `source` chains.
55 #[stable(feature = "rust1", since = "1.0.0")]
56 #[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
57 pub trait Error: Debug + Display {
58 /// The lower-level source of this error, if any.
63 /// use std::error::Error;
67 /// struct SuperError {
68 /// source: SuperErrorSideKick,
71 /// impl fmt::Display for SuperError {
72 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 /// write!(f, "SuperError is here!")
77 /// impl Error for SuperError {
78 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
79 /// Some(&self.source)
84 /// struct SuperErrorSideKick;
86 /// impl fmt::Display for SuperErrorSideKick {
87 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 /// write!(f, "SuperErrorSideKick is here!")
92 /// impl Error for SuperErrorSideKick {}
94 /// fn get_super_error() -> Result<(), SuperError> {
95 /// Err(SuperError { source: SuperErrorSideKick })
99 /// match get_super_error() {
101 /// println!("Error: {e}");
102 /// println!("Caused by: {}", e.source().unwrap());
104 /// _ => println!("No error"),
108 #[stable(feature = "error_source", since = "1.30.0")]
109 fn source(&self) -> Option<&(dyn Error + 'static)> {
113 /// Gets the `TypeId` of `self`.
116 feature = "error_type_id",
117 reason = "this is memory-unsafe to override in user code",
120 fn type_id(&self, _: private::Internal) -> TypeId
127 /// Returns a stack backtrace, if available, of where this error occurred.
129 /// This function allows inspecting the location, in code, of where an error
130 /// happened. The returned `Backtrace` contains information about the stack
131 /// trace of the OS thread of execution of where the error originated from.
133 /// Note that not all errors contain a `Backtrace`. Also note that a
134 /// `Backtrace` may actually be empty. For more information consult the
135 /// `Backtrace` type itself.
136 #[unstable(feature = "backtrace", issue = "53487")]
137 fn backtrace(&self) -> Option<&Backtrace> {
142 /// if let Err(e) = "xc".parse::<u32>() {
143 /// // Print `e` itself, no need for description().
144 /// eprintln!("Error: {e}");
147 #[stable(feature = "rust1", since = "1.0.0")]
148 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
149 fn description(&self) -> &str {
150 "description() is deprecated; use Display"
153 #[stable(feature = "rust1", since = "1.0.0")]
156 reason = "replaced by Error::source, which can support downcasting"
158 #[allow(missing_docs)]
159 fn cause(&self) -> Option<&dyn Error> {
165 // This is a hack to prevent `type_id` from being overridden by `Error`
166 // implementations, since that can enable unsound downcasting.
167 #[unstable(feature = "error_type_id", issue = "60784")]
172 #[stable(feature = "rust1", since = "1.0.0")]
173 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
174 /// Converts a type of [`Error`] into a box of dyn [`Error`].
179 /// use std::error::Error;
186 /// impl fmt::Display for AnError {
187 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188 /// write!(f, "An error")
192 /// impl Error for AnError {}
194 /// let an_error = AnError;
195 /// assert!(0 == mem::size_of_val(&an_error));
196 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
197 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
199 fn from(err: E) -> Box<dyn Error + 'a> {
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
206 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
207 /// dyn [`Error`] + [`Send`] + [`Sync`].
212 /// use std::error::Error;
219 /// impl fmt::Display for AnError {
220 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
221 /// write!(f, "An error")
225 /// impl Error for AnError {}
227 /// unsafe impl Send for AnError {}
229 /// unsafe impl Sync for AnError {}
231 /// let an_error = AnError;
232 /// assert!(0 == mem::size_of_val(&an_error));
233 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
235 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
237 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl From<String> for Box<dyn Error + Send + Sync> {
244 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
249 /// use std::error::Error;
252 /// let a_string_error = "a string error".to_string();
253 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
255 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
258 fn from(err: String) -> Box<dyn Error + Send + Sync> {
259 struct StringError(String);
261 impl Error for StringError {
263 fn description(&self) -> &str {
268 impl Display for StringError {
269 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270 Display::fmt(&self.0, f)
274 // Purposefully skip printing "StringError(..)"
275 impl Debug for StringError {
276 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277 Debug::fmt(&self.0, f)
281 Box::new(StringError(err))
285 #[stable(feature = "string_box_error", since = "1.6.0")]
286 impl From<String> for Box<dyn Error> {
287 /// Converts a [`String`] into a box of dyn [`Error`].
292 /// use std::error::Error;
295 /// let a_string_error = "a string error".to_string();
296 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
297 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
299 fn from(str_err: String) -> Box<dyn Error> {
300 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
301 let err2: Box<dyn Error> = err1;
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
308 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
310 /// [`str`]: prim@str
315 /// use std::error::Error;
318 /// let a_str_error = "a str error";
319 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
321 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
324 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
325 From::from(String::from(err))
329 #[stable(feature = "string_box_error", since = "1.6.0")]
330 impl From<&str> for Box<dyn Error> {
331 /// Converts a [`str`] into a box of dyn [`Error`].
333 /// [`str`]: prim@str
338 /// use std::error::Error;
341 /// let a_str_error = "a str error";
342 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
343 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
345 fn from(err: &str) -> Box<dyn Error> {
346 From::from(String::from(err))
350 #[stable(feature = "cow_box_error", since = "1.22.0")]
351 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
352 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
357 /// use std::error::Error;
359 /// use std::borrow::Cow;
361 /// let a_cow_str_error = Cow::from("a str error");
362 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
364 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
366 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
367 From::from(String::from(err))
371 #[stable(feature = "cow_box_error", since = "1.22.0")]
372 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
373 /// Converts a [`Cow`] into a box of dyn [`Error`].
378 /// use std::error::Error;
380 /// use std::borrow::Cow;
382 /// let a_cow_str_error = Cow::from("a str error");
383 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
384 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
386 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
387 From::from(String::from(err))
391 #[unstable(feature = "never_type", issue = "35121")]
395 feature = "allocator_api",
396 reason = "the precise API and guarantees it provides may be tweaked.",
399 impl Error for AllocError {}
401 #[stable(feature = "alloc_layout", since = "1.28.0")]
402 impl Error for LayoutError {}
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl Error for str::ParseBoolError {
407 fn description(&self) -> &str {
408 "failed to parse bool"
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl Error for str::Utf8Error {
415 fn description(&self) -> &str {
416 "invalid utf-8: corrupt contents"
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl Error for num::ParseIntError {
423 fn description(&self) -> &str {
428 #[stable(feature = "try_from", since = "1.34.0")]
429 impl Error for num::TryFromIntError {
431 fn description(&self) -> &str {
436 #[stable(feature = "try_from", since = "1.34.0")]
437 impl Error for array::TryFromSliceError {
439 fn description(&self) -> &str {
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl Error for num::ParseFloatError {
447 fn description(&self) -> &str {
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl Error for string::FromUtf8Error {
455 fn description(&self) -> &str {
460 #[stable(feature = "rust1", since = "1.0.0")]
461 impl Error for string::FromUtf16Error {
463 fn description(&self) -> &str {
468 #[stable(feature = "str_parse_error2", since = "1.8.0")]
469 impl Error for Infallible {
470 fn description(&self) -> &str {
475 #[stable(feature = "decode_utf16", since = "1.9.0")]
476 impl Error for char::DecodeUtf16Error {
478 fn description(&self) -> &str {
479 "unpaired surrogate found"
483 #[stable(feature = "u8_from_char", since = "1.59.0")]
484 impl Error for char::TryFromCharError {}
486 #[unstable(feature = "map_try_insert", issue = "82766")]
487 impl<'a, K: Debug + Ord, V: Debug> Error
488 for crate::collections::btree_map::OccupiedError<'a, K, V>
491 fn description(&self) -> &str {
496 #[unstable(feature = "map_try_insert", issue = "82766")]
497 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
499 fn description(&self) -> &str {
504 #[stable(feature = "box_error", since = "1.8.0")]
505 impl<T: Error> Error for Box<T> {
506 #[allow(deprecated, deprecated_in_future)]
507 fn description(&self) -> &str {
508 Error::description(&**self)
512 fn cause(&self) -> Option<&dyn Error> {
513 Error::cause(&**self)
516 fn source(&self) -> Option<&(dyn Error + 'static)> {
517 Error::source(&**self)
521 #[unstable(feature = "thin_box", issue = "92791")]
522 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
523 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
524 use core::ops::Deref;
525 self.deref().source()
529 #[stable(feature = "error_by_ref", since = "1.51.0")]
530 impl<'a, T: Error + ?Sized> Error for &'a T {
531 #[allow(deprecated, deprecated_in_future)]
532 fn description(&self) -> &str {
533 Error::description(&**self)
537 fn cause(&self) -> Option<&dyn Error> {
538 Error::cause(&**self)
541 fn source(&self) -> Option<&(dyn Error + 'static)> {
542 Error::source(&**self)
545 fn backtrace(&self) -> Option<&Backtrace> {
546 Error::backtrace(&**self)
550 #[stable(feature = "arc_error", since = "1.52.0")]
551 impl<T: Error + ?Sized> Error for Arc<T> {
552 #[allow(deprecated, deprecated_in_future)]
553 fn description(&self) -> &str {
554 Error::description(&**self)
558 fn cause(&self) -> Option<&dyn Error> {
559 Error::cause(&**self)
562 fn source(&self) -> Option<&(dyn Error + 'static)> {
563 Error::source(&**self)
566 fn backtrace(&self) -> Option<&Backtrace> {
567 Error::backtrace(&**self)
571 #[stable(feature = "fmt_error", since = "1.11.0")]
572 impl Error for fmt::Error {
574 fn description(&self) -> &str {
575 "an error occurred when formatting an argument"
579 #[stable(feature = "try_borrow", since = "1.13.0")]
580 impl Error for cell::BorrowError {
582 fn description(&self) -> &str {
583 "already mutably borrowed"
587 #[stable(feature = "try_borrow", since = "1.13.0")]
588 impl Error for cell::BorrowMutError {
590 fn description(&self) -> &str {
595 #[stable(feature = "try_from", since = "1.34.0")]
596 impl Error for char::CharTryFromError {
598 fn description(&self) -> &str {
599 "converted integer out of range for `char`"
603 #[stable(feature = "char_from_str", since = "1.20.0")]
604 impl Error for char::ParseCharError {
606 fn description(&self) -> &str {
611 #[stable(feature = "try_reserve", since = "1.57.0")]
612 impl Error for alloc::collections::TryReserveError {}
614 #[unstable(feature = "duration_checked_float", issue = "83400")]
615 impl Error for time::FromFloatSecsError {}
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl Error for alloc::ffi::NulError {
620 fn description(&self) -> &str {
621 "nul byte found in data"
625 #[stable(feature = "rust1", since = "1.0.0")]
626 impl From<alloc::ffi::NulError> for io::Error {
627 /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
628 fn from(_: alloc::ffi::NulError) -> io::Error {
629 io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
633 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
634 impl Error for core::ffi::FromBytesWithNulError {
636 fn description(&self) -> &str {
641 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
642 impl Error for core::ffi::FromBytesUntilNulError {}
644 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
645 impl Error for alloc::ffi::FromVecWithNulError {}
647 #[stable(feature = "cstring_into", since = "1.7.0")]
648 impl Error for alloc::ffi::IntoStringError {
650 fn description(&self) -> &str {
651 "C string contained non-utf8 bytes"
654 fn source(&self) -> Option<&(dyn Error + 'static)> {
655 Some(self.__source())
659 // Copied from `any.rs`.
660 impl dyn Error + 'static {
661 /// Returns `true` if the inner type is the same as `T`.
662 #[stable(feature = "error_downcast", since = "1.3.0")]
664 pub fn is<T: Error + 'static>(&self) -> bool {
665 // Get `TypeId` of the type this function is instantiated with.
666 let t = TypeId::of::<T>();
668 // Get `TypeId` of the type in the trait object (`self`).
669 let concrete = self.type_id(private::Internal);
671 // Compare both `TypeId`s on equality.
675 /// Returns some reference to the inner value if it is of type `T`, or
676 /// `None` if it isn't.
677 #[stable(feature = "error_downcast", since = "1.3.0")]
679 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
681 unsafe { Some(&*(self as *const dyn Error as *const T)) }
687 /// Returns some mutable reference to the inner value if it is of type `T`, or
688 /// `None` if it isn't.
689 #[stable(feature = "error_downcast", since = "1.3.0")]
691 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
693 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
700 impl dyn Error + 'static + Send {
701 /// Forwards to the method defined on the type `dyn Error`.
702 #[stable(feature = "error_downcast", since = "1.3.0")]
704 pub fn is<T: Error + 'static>(&self) -> bool {
705 <dyn Error + 'static>::is::<T>(self)
708 /// Forwards to the method defined on the type `dyn Error`.
709 #[stable(feature = "error_downcast", since = "1.3.0")]
711 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
712 <dyn Error + 'static>::downcast_ref::<T>(self)
715 /// Forwards to the method defined on the type `dyn Error`.
716 #[stable(feature = "error_downcast", since = "1.3.0")]
718 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
719 <dyn Error + 'static>::downcast_mut::<T>(self)
723 impl dyn Error + 'static + Send + Sync {
724 /// Forwards to the method defined on the type `dyn Error`.
725 #[stable(feature = "error_downcast", since = "1.3.0")]
727 pub fn is<T: Error + 'static>(&self) -> bool {
728 <dyn Error + 'static>::is::<T>(self)
731 /// Forwards to the method defined on the type `dyn Error`.
732 #[stable(feature = "error_downcast", since = "1.3.0")]
734 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
735 <dyn Error + 'static>::downcast_ref::<T>(self)
738 /// Forwards to the method defined on the type `dyn Error`.
739 #[stable(feature = "error_downcast", since = "1.3.0")]
741 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
742 <dyn Error + 'static>::downcast_mut::<T>(self)
748 #[stable(feature = "error_downcast", since = "1.3.0")]
749 /// Attempts to downcast the box to a concrete type.
750 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
753 let raw: *mut dyn Error = Box::into_raw(self);
754 Ok(Box::from_raw(raw as *mut T))
761 /// Returns an iterator starting with the current error and continuing with
762 /// recursively calling [`Error::source`].
764 /// If you want to omit the current error and only use its sources,
770 /// #![feature(error_iter)]
771 /// use std::error::Error;
778 /// struct B(Option<Box<dyn Error + 'static>>);
780 /// impl fmt::Display for A {
781 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
786 /// impl fmt::Display for B {
787 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792 /// impl Error for A {}
794 /// impl Error for B {
795 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
796 /// self.0.as_ref().map(|e| e.as_ref())
800 /// let b = B(Some(Box::new(A)));
802 /// // let err : Box<Error> = b.into(); // or
803 /// let err = &b as &(dyn Error);
805 /// let mut iter = err.chain();
807 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
808 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
809 /// assert!(iter.next().is_none());
810 /// assert!(iter.next().is_none());
812 #[unstable(feature = "error_iter", issue = "58520")]
814 pub fn chain(&self) -> Chain<'_> {
815 Chain { current: Some(self) }
819 /// An iterator over an [`Error`] and its sources.
821 /// If you want to omit the initial error and only process
822 /// its sources, use `skip(1)`.
823 #[unstable(feature = "error_iter", issue = "58520")]
824 #[derive(Clone, Debug)]
825 pub struct Chain<'a> {
826 current: Option<&'a (dyn Error + 'static)>,
829 #[unstable(feature = "error_iter", issue = "58520")]
830 impl<'a> Iterator for Chain<'a> {
831 type Item = &'a (dyn Error + 'static);
833 fn next(&mut self) -> Option<Self::Item> {
834 let current = self.current;
835 self.current = self.current.and_then(Error::source);
840 impl dyn Error + Send {
842 #[stable(feature = "error_downcast", since = "1.3.0")]
843 /// Attempts to downcast the box to a concrete type.
844 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
845 let err: Box<dyn Error> = self;
846 <dyn Error>::downcast(err).map_err(|s| unsafe {
847 // Reapply the `Send` marker.
848 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
853 impl dyn Error + Send + Sync {
855 #[stable(feature = "error_downcast", since = "1.3.0")]
856 /// Attempts to downcast the box to a concrete type.
857 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
858 let err: Box<dyn Error> = self;
859 <dyn Error>::downcast(err).map_err(|s| unsafe {
860 // Reapply the `Send + Sync` marker.
861 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
866 /// An error reporter that print's an error and its sources.
868 /// Report also exposes configuration options for formatting the error chain, either entirely on a
869 /// single line, or in multi-line format with each cause in the error chain on a new line.
871 /// `Report` only requires that the wrapped error implements `Error`. It doesn't require that the
872 /// wrapped error be `Send`, `Sync`, or `'static`.
877 /// #![feature(error_reporter)]
878 /// use std::error::{Error, Report};
882 /// struct SuperError {
883 /// source: SuperErrorSideKick,
886 /// impl fmt::Display for SuperError {
887 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
888 /// write!(f, "SuperError is here!")
892 /// impl Error for SuperError {
893 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
894 /// Some(&self.source)
899 /// struct SuperErrorSideKick;
901 /// impl fmt::Display for SuperErrorSideKick {
902 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 /// write!(f, "SuperErrorSideKick is here!")
907 /// impl Error for SuperErrorSideKick {}
909 /// fn get_super_error() -> Result<(), SuperError> {
910 /// Err(SuperError { source: SuperErrorSideKick })
914 /// match get_super_error() {
915 /// Err(e) => println!("Error: {}", Report::new(e)),
916 /// _ => println!("No error"),
921 /// This example produces the following output:
924 /// Error: SuperError is here!: SuperErrorSideKick is here!
927 /// ## Output consistency
929 /// Report prints the same output via `Display` and `Debug`, so it works well with
930 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
933 /// #![feature(error_reporter)]
934 /// use std::error::Report;
935 /// # use std::error::Error;
937 /// # #[derive(Debug)]
938 /// # struct SuperError {
939 /// # source: SuperErrorSideKick,
941 /// # impl fmt::Display for SuperError {
942 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
943 /// # write!(f, "SuperError is here!")
946 /// # impl Error for SuperError {
947 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
948 /// # Some(&self.source)
951 /// # #[derive(Debug)]
952 /// # struct SuperErrorSideKick;
953 /// # impl fmt::Display for SuperErrorSideKick {
954 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955 /// # write!(f, "SuperErrorSideKick is here!")
958 /// # impl Error for SuperErrorSideKick {}
959 /// # fn get_super_error() -> Result<(), SuperError> {
960 /// # Err(SuperError { source: SuperErrorSideKick })
963 /// get_super_error().map_err(Report::new).unwrap();
966 /// This example produces the following output:
969 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
970 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
973 /// ## Return from `main`
975 /// `Report` also implements `From` for all types that implement [`Error`], this when combined with
976 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
980 /// #![feature(error_reporter)]
981 /// use std::error::Report;
982 /// # use std::error::Error;
984 /// # #[derive(Debug)]
985 /// # struct SuperError {
986 /// # source: SuperErrorSideKick,
988 /// # impl fmt::Display for SuperError {
989 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990 /// # write!(f, "SuperError is here!")
993 /// # impl Error for SuperError {
994 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
995 /// # Some(&self.source)
998 /// # #[derive(Debug)]
999 /// # struct SuperErrorSideKick;
1000 /// # impl fmt::Display for SuperErrorSideKick {
1001 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1002 /// # write!(f, "SuperErrorSideKick is here!")
1005 /// # impl Error for SuperErrorSideKick {}
1006 /// # fn get_super_error() -> Result<(), SuperError> {
1007 /// # Err(SuperError { source: SuperErrorSideKick })
1010 /// fn main() -> Result<(), Report> {
1011 /// get_super_error()?;
1016 /// This example produces the following output:
1019 /// Error: SuperError is here!: SuperErrorSideKick is here!
1022 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1023 /// output format, if you want to make sure your `Report`s are pretty printed and include backtrace
1024 /// you will need to manually convert and enable those flags.
1027 /// #![feature(error_reporter)]
1028 /// use std::error::Report;
1029 /// # use std::error::Error;
1031 /// # #[derive(Debug)]
1032 /// # struct SuperError {
1033 /// # source: SuperErrorSideKick,
1035 /// # impl fmt::Display for SuperError {
1036 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1037 /// # write!(f, "SuperError is here!")
1040 /// # impl Error for SuperError {
1041 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1042 /// # Some(&self.source)
1045 /// # #[derive(Debug)]
1046 /// # struct SuperErrorSideKick;
1047 /// # impl fmt::Display for SuperErrorSideKick {
1048 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1049 /// # write!(f, "SuperErrorSideKick is here!")
1052 /// # impl Error for SuperErrorSideKick {}
1053 /// # fn get_super_error() -> Result<(), SuperError> {
1054 /// # Err(SuperError { source: SuperErrorSideKick })
1057 /// fn main() -> Result<(), Report> {
1058 /// get_super_error()
1059 /// .map_err(Report::from)
1060 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1065 /// This example produces the following output:
1068 /// Error: SuperError is here!
1071 /// SuperErrorSideKick is here!
1073 #[unstable(feature = "error_reporter", issue = "90172")]
1074 pub struct Report<E = Box<dyn Error>> {
1075 /// The error being reported.
1077 /// Whether a backtrace should be included as part of the report.
1078 show_backtrace: bool,
1079 /// Whether the report should be pretty-printed.
1087 /// Create a new `Report` from an input error.
1088 #[unstable(feature = "error_reporter", issue = "90172")]
1089 pub fn new(error: E) -> Report<E> {
1095 /// Enable pretty-printing the report across multiple lines.
1100 /// #![feature(error_reporter)]
1101 /// use std::error::Report;
1102 /// # use std::error::Error;
1104 /// # #[derive(Debug)]
1105 /// # struct SuperError {
1106 /// # source: SuperErrorSideKick,
1108 /// # impl fmt::Display for SuperError {
1109 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1110 /// # write!(f, "SuperError is here!")
1113 /// # impl Error for SuperError {
1114 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1115 /// # Some(&self.source)
1118 /// # #[derive(Debug)]
1119 /// # struct SuperErrorSideKick;
1120 /// # impl fmt::Display for SuperErrorSideKick {
1121 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1122 /// # write!(f, "SuperErrorSideKick is here!")
1125 /// # impl Error for SuperErrorSideKick {}
1127 /// let error = SuperError { source: SuperErrorSideKick };
1128 /// let report = Report::new(error).pretty(true);
1129 /// eprintln!("Error: {report:?}");
1132 /// This example produces the following output:
1135 /// Error: SuperError is here!
1138 /// SuperErrorSideKick is here!
1141 /// When there are multiple source errors the causes will be numbered in order of iteration
1142 /// starting from the outermost error.
1145 /// #![feature(error_reporter)]
1146 /// use std::error::Report;
1147 /// # use std::error::Error;
1149 /// # #[derive(Debug)]
1150 /// # struct SuperError {
1151 /// # source: SuperErrorSideKick,
1153 /// # impl fmt::Display for SuperError {
1154 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1155 /// # write!(f, "SuperError is here!")
1158 /// # impl Error for SuperError {
1159 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1160 /// # Some(&self.source)
1163 /// # #[derive(Debug)]
1164 /// # struct SuperErrorSideKick {
1165 /// # source: SuperErrorSideKickSideKick,
1167 /// # impl fmt::Display for SuperErrorSideKick {
1168 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1169 /// # write!(f, "SuperErrorSideKick is here!")
1172 /// # impl Error for SuperErrorSideKick {
1173 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1174 /// # Some(&self.source)
1177 /// # #[derive(Debug)]
1178 /// # struct SuperErrorSideKickSideKick;
1179 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1180 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1181 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1184 /// # impl Error for SuperErrorSideKickSideKick { }
1186 /// let source = SuperErrorSideKickSideKick;
1187 /// let source = SuperErrorSideKick { source };
1188 /// let error = SuperError { source };
1189 /// let report = Report::new(error).pretty(true);
1190 /// eprintln!("Error: {report:?}");
1193 /// This example produces the following output:
1196 /// Error: SuperError is here!
1199 /// 0: SuperErrorSideKick is here!
1200 /// 1: SuperErrorSideKickSideKick is here!
1202 #[unstable(feature = "error_reporter", issue = "90172")]
1203 pub fn pretty(mut self, pretty: bool) -> Self {
1204 self.pretty = pretty;
1208 /// Display backtrace if available when using pretty output format.
1212 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1213 /// outermost error. In this example it will display the backtrace from the second error in the
1214 /// chain, `SuperErrorSideKick`.
1217 /// #![feature(error_reporter)]
1218 /// #![feature(backtrace)]
1219 /// # use std::error::Error;
1221 /// use std::error::Report;
1222 /// use std::backtrace::Backtrace;
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 /// backtrace: Backtrace,
1243 /// impl SuperErrorSideKick {
1244 /// fn new() -> SuperErrorSideKick {
1245 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1249 /// impl Error for SuperErrorSideKick {
1250 /// fn backtrace(&self) -> Option<&Backtrace> {
1251 /// Some(&self.backtrace)
1255 /// // The rest of the example is unchanged ...
1256 /// # impl fmt::Display for SuperErrorSideKick {
1257 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1258 /// # write!(f, "SuperErrorSideKick is here!")
1262 /// let source = SuperErrorSideKick::new();
1263 /// let error = SuperError { source };
1264 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1265 /// eprintln!("Error: {report:?}");
1268 /// This example produces something similar to the following output:
1271 /// Error: SuperError is here!
1274 /// SuperErrorSideKick is here!
1276 /// Stack backtrace:
1277 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1278 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1279 /// 2: rust_out::main
1280 /// 3: core::ops::function::FnOnce::call_once
1281 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1282 /// 5: std::rt::lang_start::{{closure}}
1283 /// 6: std::panicking::try
1284 /// 7: std::rt::lang_start_internal
1285 /// 8: std::rt::lang_start
1287 /// 10: __libc_start_main
1290 #[unstable(feature = "error_reporter", issue = "90172")]
1291 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1292 self.show_backtrace = show_backtrace;
1301 fn backtrace(&self) -> Option<&Backtrace> {
1302 // have to grab the backtrace on the first error directly since that error may not be
1304 let backtrace = self.error.backtrace();
1305 let backtrace = backtrace.or_else(|| {
1308 .map(|source| source.chain().find_map(|source| source.backtrace()))
1314 /// Format the report as a single line.
1315 #[unstable(feature = "error_reporter", issue = "90172")]
1316 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1317 write!(f, "{}", self.error)?;
1319 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1321 for cause in sources {
1322 write!(f, ": {cause}")?;
1328 /// Format the report as multiple lines, with each error cause on its own line.
1329 #[unstable(feature = "error_reporter", issue = "90172")]
1330 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1331 let error = &self.error;
1333 write!(f, "{error}")?;
1335 if let Some(cause) = error.source() {
1336 write!(f, "\n\nCaused by:")?;
1338 let multiple = cause.source().is_some();
1340 for (ind, error) in cause.chain().enumerate() {
1342 let mut indented = Indented { inner: f };
1344 write!(indented, "{ind: >4}: {error}")?;
1346 write!(indented, " {error}")?;
1351 if self.show_backtrace {
1352 let backtrace = self.backtrace();
1354 if let Some(backtrace) = backtrace {
1355 let backtrace = backtrace.to_string();
1357 f.write_str("\n\nStack backtrace:\n")?;
1358 f.write_str(backtrace.trim_end())?;
1366 impl Report<Box<dyn Error>> {
1367 fn backtrace(&self) -> Option<&Backtrace> {
1368 // have to grab the backtrace on the first error directly since that error may not be
1370 let backtrace = self.error.backtrace();
1371 let backtrace = backtrace.or_else(|| {
1374 .map(|source| source.chain().find_map(|source| source.backtrace()))
1380 /// Format the report as a single line.
1381 #[unstable(feature = "error_reporter", issue = "90172")]
1382 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1383 write!(f, "{}", self.error)?;
1385 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1387 for cause in sources {
1388 write!(f, ": {cause}")?;
1394 /// Format the report as multiple lines, with each error cause on its own line.
1395 #[unstable(feature = "error_reporter", issue = "90172")]
1396 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1397 let error = &self.error;
1399 write!(f, "{error}")?;
1401 if let Some(cause) = error.source() {
1402 write!(f, "\n\nCaused by:")?;
1404 let multiple = cause.source().is_some();
1406 for (ind, error) in cause.chain().enumerate() {
1408 let mut indented = Indented { inner: f };
1410 write!(indented, "{ind: >4}: {error}")?;
1412 write!(indented, " {error}")?;
1417 if self.show_backtrace {
1418 let backtrace = self.backtrace();
1420 if let Some(backtrace) = backtrace {
1421 let backtrace = backtrace.to_string();
1423 f.write_str("\n\nStack backtrace:\n")?;
1424 f.write_str(backtrace.trim_end())?;
1432 #[unstable(feature = "error_reporter", issue = "90172")]
1433 impl<E> From<E> for Report<E>
1437 fn from(error: E) -> Self {
1438 Report { error, show_backtrace: false, pretty: false }
1442 #[unstable(feature = "error_reporter", issue = "90172")]
1443 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1447 fn from(error: E) -> Self {
1448 let error = box error;
1449 Report { error, show_backtrace: false, pretty: false }
1453 #[unstable(feature = "error_reporter", issue = "90172")]
1454 impl<E> fmt::Display for Report<E>
1458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1459 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1463 #[unstable(feature = "error_reporter", issue = "90172")]
1464 impl fmt::Display for Report<Box<dyn Error>> {
1465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1466 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1470 // This type intentionally outputs the same format for `Display` and `Debug`for
1471 // situations where you unwrap a `Report` or return it from main.
1472 #[unstable(feature = "error_reporter", issue = "90172")]
1473 impl<E> fmt::Debug for Report<E>
1475 Report<E>: fmt::Display,
1477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478 fmt::Display::fmt(self, f)
1482 /// Wrapper type for indenting the inner source.
1483 struct Indented<'a, D> {
1487 impl<T> Write for Indented<'_, T>
1491 fn write_str(&mut self, s: &str) -> fmt::Result {
1492 for (i, line) in s.split('\n').enumerate() {
1494 self.inner.write_char('\n')?;
1495 self.inner.write_str(" ")?;
1498 self.inner.write_str(line)?;