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 pub trait Error: Debug + Display {
57 /// The lower-level source of this error, if any.
62 /// use std::error::Error;
66 /// struct SuperError {
67 /// source: SuperErrorSideKick,
70 /// impl fmt::Display for SuperError {
71 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 /// write!(f, "SuperError is here!")
76 /// impl Error for SuperError {
77 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
78 /// Some(&self.source)
83 /// struct SuperErrorSideKick;
85 /// impl fmt::Display for SuperErrorSideKick {
86 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 /// write!(f, "SuperErrorSideKick is here!")
91 /// impl Error for SuperErrorSideKick {}
93 /// fn get_super_error() -> Result<(), SuperError> {
94 /// Err(SuperError { source: SuperErrorSideKick })
98 /// match get_super_error() {
100 /// println!("Error: {e}");
101 /// println!("Caused by: {}", e.source().unwrap());
103 /// _ => println!("No error"),
107 #[stable(feature = "error_source", since = "1.30.0")]
108 fn source(&self) -> Option<&(dyn Error + 'static)> {
112 /// Gets the `TypeId` of `self`.
115 feature = "error_type_id",
116 reason = "this is memory-unsafe to override in user code",
119 fn type_id(&self, _: private::Internal) -> TypeId
126 /// Returns a stack backtrace, if available, of where this error occurred.
128 /// This function allows inspecting the location, in code, of where an error
129 /// happened. The returned `Backtrace` contains information about the stack
130 /// trace of the OS thread of execution of where the error originated from.
132 /// Note that not all errors contain a `Backtrace`. Also note that a
133 /// `Backtrace` may actually be empty. For more information consult the
134 /// `Backtrace` type itself.
135 #[unstable(feature = "backtrace", issue = "53487")]
136 fn backtrace(&self) -> Option<&Backtrace> {
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 #[rustc_deprecated(since = "1.42.0", reason = "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 reason = "replaced by Error::source, which can support downcasting"
157 #[allow(missing_docs)]
158 fn cause(&self) -> Option<&dyn Error> {
164 // This is a hack to prevent `type_id` from being overridden by `Error`
165 // implementations, since that can enable unsound downcasting.
166 #[unstable(feature = "error_type_id", issue = "60784")]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
173 /// Converts a type of [`Error`] into a box of dyn [`Error`].
178 /// use std::error::Error;
185 /// impl fmt::Display for AnError {
186 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187 /// write!(f, "An error")
191 /// impl Error for AnError {}
193 /// let an_error = AnError;
194 /// assert!(0 == mem::size_of_val(&an_error));
195 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
196 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
198 fn from(err: E) -> Box<dyn Error + 'a> {
203 #[stable(feature = "rust1", since = "1.0.0")]
204 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
205 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
206 /// dyn [`Error`] + [`Send`] + [`Sync`].
211 /// use std::error::Error;
218 /// impl fmt::Display for AnError {
219 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 /// write!(f, "An error")
224 /// impl Error for AnError {}
226 /// unsafe impl Send for AnError {}
228 /// unsafe impl Sync for AnError {}
230 /// let an_error = AnError;
231 /// assert!(0 == mem::size_of_val(&an_error));
232 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
234 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
236 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl From<String> for Box<dyn Error + Send + Sync> {
243 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
248 /// use std::error::Error;
251 /// let a_string_error = "a string error".to_string();
252 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
254 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
257 fn from(err: String) -> Box<dyn Error + Send + Sync> {
258 struct StringError(String);
260 impl Error for StringError {
262 fn description(&self) -> &str {
267 impl Display for StringError {
268 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 Display::fmt(&self.0, f)
273 // Purposefully skip printing "StringError(..)"
274 impl Debug for StringError {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 Debug::fmt(&self.0, f)
280 Box::new(StringError(err))
284 #[stable(feature = "string_box_error", since = "1.6.0")]
285 impl From<String> for Box<dyn Error> {
286 /// Converts a [`String`] into a box of dyn [`Error`].
291 /// use std::error::Error;
294 /// let a_string_error = "a string error".to_string();
295 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
296 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
298 fn from(str_err: String) -> Box<dyn Error> {
299 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
300 let err2: Box<dyn Error> = err1;
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
307 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
309 /// [`str`]: prim@str
314 /// use std::error::Error;
317 /// let a_str_error = "a str error";
318 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
320 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
323 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
324 From::from(String::from(err))
328 #[stable(feature = "string_box_error", since = "1.6.0")]
329 impl From<&str> for Box<dyn Error> {
330 /// Converts a [`str`] into a box of dyn [`Error`].
332 /// [`str`]: prim@str
337 /// use std::error::Error;
340 /// let a_str_error = "a str error";
341 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
342 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
344 fn from(err: &str) -> Box<dyn Error> {
345 From::from(String::from(err))
349 #[stable(feature = "cow_box_error", since = "1.22.0")]
350 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
351 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
356 /// use std::error::Error;
358 /// use std::borrow::Cow;
360 /// let a_cow_str_error = Cow::from("a str error");
361 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
363 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
365 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
366 From::from(String::from(err))
370 #[stable(feature = "cow_box_error", since = "1.22.0")]
371 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
372 /// Converts a [`Cow`] into a box of dyn [`Error`].
377 /// use std::error::Error;
379 /// use std::borrow::Cow;
381 /// let a_cow_str_error = Cow::from("a str error");
382 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
383 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
385 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
386 From::from(String::from(err))
390 #[unstable(feature = "never_type", issue = "35121")]
394 feature = "allocator_api",
395 reason = "the precise API and guarantees it provides may be tweaked.",
398 impl Error for AllocError {}
400 #[stable(feature = "alloc_layout", since = "1.28.0")]
401 impl Error for LayoutError {}
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl Error for str::ParseBoolError {
406 fn description(&self) -> &str {
407 "failed to parse bool"
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl Error for str::Utf8Error {
414 fn description(&self) -> &str {
415 "invalid utf-8: corrupt contents"
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl Error for num::ParseIntError {
422 fn description(&self) -> &str {
427 #[stable(feature = "try_from", since = "1.34.0")]
428 impl Error for num::TryFromIntError {
430 fn description(&self) -> &str {
435 #[stable(feature = "try_from", since = "1.34.0")]
436 impl Error for array::TryFromSliceError {
438 fn description(&self) -> &str {
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl Error for num::ParseFloatError {
446 fn description(&self) -> &str {
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl Error for string::FromUtf8Error {
454 fn description(&self) -> &str {
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl Error for string::FromUtf16Error {
462 fn description(&self) -> &str {
467 #[stable(feature = "str_parse_error2", since = "1.8.0")]
468 impl Error for Infallible {
469 fn description(&self) -> &str {
474 #[stable(feature = "decode_utf16", since = "1.9.0")]
475 impl Error for char::DecodeUtf16Error {
477 fn description(&self) -> &str {
478 "unpaired surrogate found"
482 #[stable(feature = "u8_from_char", since = "1.59.0")]
483 impl Error for char::TryFromCharError {}
485 #[unstable(feature = "map_try_insert", issue = "82766")]
486 impl<'a, K: Debug + Ord, V: Debug> Error
487 for crate::collections::btree_map::OccupiedError<'a, K, V>
490 fn description(&self) -> &str {
495 #[unstable(feature = "map_try_insert", issue = "82766")]
496 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
498 fn description(&self) -> &str {
503 #[stable(feature = "box_error", since = "1.8.0")]
504 impl<T: Error> Error for Box<T> {
505 #[allow(deprecated, deprecated_in_future)]
506 fn description(&self) -> &str {
507 Error::description(&**self)
511 fn cause(&self) -> Option<&dyn Error> {
512 Error::cause(&**self)
515 fn source(&self) -> Option<&(dyn Error + 'static)> {
516 Error::source(&**self)
520 #[unstable(feature = "thin_box", issue = "92791")]
521 impl<T: ?Sized + crate::error::Error> crate::error::Error for crate::boxed::ThinBox<T> {
522 fn source(&self) -> Option<&(dyn crate::error::Error + 'static)> {
523 use core::ops::Deref;
524 self.deref().source()
528 #[stable(feature = "error_by_ref", since = "1.51.0")]
529 impl<'a, T: Error + ?Sized> Error for &'a T {
530 #[allow(deprecated, deprecated_in_future)]
531 fn description(&self) -> &str {
532 Error::description(&**self)
536 fn cause(&self) -> Option<&dyn Error> {
537 Error::cause(&**self)
540 fn source(&self) -> Option<&(dyn Error + 'static)> {
541 Error::source(&**self)
544 fn backtrace(&self) -> Option<&Backtrace> {
545 Error::backtrace(&**self)
549 #[stable(feature = "arc_error", since = "1.52.0")]
550 impl<T: Error + ?Sized> Error for Arc<T> {
551 #[allow(deprecated, deprecated_in_future)]
552 fn description(&self) -> &str {
553 Error::description(&**self)
557 fn cause(&self) -> Option<&dyn Error> {
558 Error::cause(&**self)
561 fn source(&self) -> Option<&(dyn Error + 'static)> {
562 Error::source(&**self)
565 fn backtrace(&self) -> Option<&Backtrace> {
566 Error::backtrace(&**self)
570 #[stable(feature = "fmt_error", since = "1.11.0")]
571 impl Error for fmt::Error {
573 fn description(&self) -> &str {
574 "an error occurred when formatting an argument"
578 #[stable(feature = "try_borrow", since = "1.13.0")]
579 impl Error for cell::BorrowError {
581 fn description(&self) -> &str {
582 "already mutably borrowed"
586 #[stable(feature = "try_borrow", since = "1.13.0")]
587 impl Error for cell::BorrowMutError {
589 fn description(&self) -> &str {
594 #[stable(feature = "try_from", since = "1.34.0")]
595 impl Error for char::CharTryFromError {
597 fn description(&self) -> &str {
598 "converted integer out of range for `char`"
602 #[stable(feature = "char_from_str", since = "1.20.0")]
603 impl Error for char::ParseCharError {
605 fn description(&self) -> &str {
610 #[stable(feature = "try_reserve", since = "1.57.0")]
611 impl Error for alloc::collections::TryReserveError {}
613 #[unstable(feature = "duration_checked_float", issue = "83400")]
614 impl Error for time::FromFloatSecsError {}
616 #[stable(feature = "rust1", since = "1.0.0")]
617 impl Error for alloc::ffi::NulError {
619 fn description(&self) -> &str {
620 "nul byte found in data"
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl From<alloc::ffi::NulError> for io::Error {
626 /// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
627 fn from(_: alloc::ffi::NulError) -> io::Error {
628 io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
632 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
633 impl Error for core::ffi::FromBytesWithNulError {
635 fn description(&self) -> &str {
640 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
641 impl Error for core::ffi::FromBytesUntilNulError {}
643 #[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
644 impl Error for alloc::ffi::FromVecWithNulError {}
646 #[stable(feature = "cstring_into", since = "1.7.0")]
647 impl Error for alloc::ffi::IntoStringError {
649 fn description(&self) -> &str {
650 "C string contained non-utf8 bytes"
653 fn source(&self) -> Option<&(dyn Error + 'static)> {
654 Some(self.__source())
658 // Copied from `any.rs`.
659 impl dyn Error + 'static {
660 /// Returns `true` if the inner type is the same as `T`.
661 #[stable(feature = "error_downcast", since = "1.3.0")]
663 pub fn is<T: Error + 'static>(&self) -> bool {
664 // Get `TypeId` of the type this function is instantiated with.
665 let t = TypeId::of::<T>();
667 // Get `TypeId` of the type in the trait object (`self`).
668 let concrete = self.type_id(private::Internal);
670 // Compare both `TypeId`s on equality.
674 /// Returns some reference to the inner value if it is of type `T`, or
675 /// `None` if it isn't.
676 #[stable(feature = "error_downcast", since = "1.3.0")]
678 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
680 unsafe { Some(&*(self as *const dyn Error as *const T)) }
686 /// Returns some mutable reference to the inner value if it is of type `T`, or
687 /// `None` if it isn't.
688 #[stable(feature = "error_downcast", since = "1.3.0")]
690 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
692 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
699 impl dyn Error + 'static + Send {
700 /// Forwards to the method defined on the type `dyn Error`.
701 #[stable(feature = "error_downcast", since = "1.3.0")]
703 pub fn is<T: Error + 'static>(&self) -> bool {
704 <dyn Error + 'static>::is::<T>(self)
707 /// Forwards to the method defined on the type `dyn Error`.
708 #[stable(feature = "error_downcast", since = "1.3.0")]
710 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
711 <dyn Error + 'static>::downcast_ref::<T>(self)
714 /// Forwards to the method defined on the type `dyn Error`.
715 #[stable(feature = "error_downcast", since = "1.3.0")]
717 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
718 <dyn Error + 'static>::downcast_mut::<T>(self)
722 impl dyn Error + 'static + Send + Sync {
723 /// Forwards to the method defined on the type `dyn Error`.
724 #[stable(feature = "error_downcast", since = "1.3.0")]
726 pub fn is<T: Error + 'static>(&self) -> bool {
727 <dyn Error + 'static>::is::<T>(self)
730 /// Forwards to the method defined on the type `dyn Error`.
731 #[stable(feature = "error_downcast", since = "1.3.0")]
733 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
734 <dyn Error + 'static>::downcast_ref::<T>(self)
737 /// Forwards to the method defined on the type `dyn Error`.
738 #[stable(feature = "error_downcast", since = "1.3.0")]
740 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
741 <dyn Error + 'static>::downcast_mut::<T>(self)
747 #[stable(feature = "error_downcast", since = "1.3.0")]
748 /// Attempts to downcast the box to a concrete type.
749 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
752 let raw: *mut dyn Error = Box::into_raw(self);
753 Ok(Box::from_raw(raw as *mut T))
760 /// Returns an iterator starting with the current error and continuing with
761 /// recursively calling [`Error::source`].
763 /// If you want to omit the current error and only use its sources,
769 /// #![feature(error_iter)]
770 /// use std::error::Error;
777 /// struct B(Option<Box<dyn Error + 'static>>);
779 /// impl fmt::Display for A {
780 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 /// impl fmt::Display for B {
786 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791 /// impl Error for A {}
793 /// impl Error for B {
794 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
795 /// self.0.as_ref().map(|e| e.as_ref())
799 /// let b = B(Some(Box::new(A)));
801 /// // let err : Box<Error> = b.into(); // or
802 /// let err = &b as &(dyn Error);
804 /// let mut iter = err.chain();
806 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
807 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
808 /// assert!(iter.next().is_none());
809 /// assert!(iter.next().is_none());
811 #[unstable(feature = "error_iter", issue = "58520")]
813 pub fn chain(&self) -> Chain<'_> {
814 Chain { current: Some(self) }
818 /// An iterator over an [`Error`] and its sources.
820 /// If you want to omit the initial error and only process
821 /// its sources, use `skip(1)`.
822 #[unstable(feature = "error_iter", issue = "58520")]
823 #[derive(Clone, Debug)]
824 pub struct Chain<'a> {
825 current: Option<&'a (dyn Error + 'static)>,
828 #[unstable(feature = "error_iter", issue = "58520")]
829 impl<'a> Iterator for Chain<'a> {
830 type Item = &'a (dyn Error + 'static);
832 fn next(&mut self) -> Option<Self::Item> {
833 let current = self.current;
834 self.current = self.current.and_then(Error::source);
839 impl dyn Error + Send {
841 #[stable(feature = "error_downcast", since = "1.3.0")]
842 /// Attempts to downcast the box to a concrete type.
843 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
844 let err: Box<dyn Error> = self;
845 <dyn Error>::downcast(err).map_err(|s| unsafe {
846 // Reapply the `Send` marker.
847 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
852 impl dyn Error + Send + Sync {
854 #[stable(feature = "error_downcast", since = "1.3.0")]
855 /// Attempts to downcast the box to a concrete type.
856 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
857 let err: Box<dyn Error> = self;
858 <dyn Error>::downcast(err).map_err(|s| unsafe {
859 // Reapply the `Send + Sync` marker.
860 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
865 /// An error reporter that print's an error and its sources.
867 /// Report also exposes configuration options for formatting the error chain, either entirely on a
868 /// single line, or in multi-line format with each cause in the error chain on a new line.
870 /// `Report` only requires that the wrapped error implements `Error`. It doesn't require that the
871 /// wrapped error be `Send`, `Sync`, or `'static`.
876 /// #![feature(error_reporter)]
877 /// use std::error::{Error, Report};
881 /// struct SuperError {
882 /// source: SuperErrorSideKick,
885 /// impl fmt::Display for SuperError {
886 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
887 /// write!(f, "SuperError is here!")
891 /// impl Error for SuperError {
892 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
893 /// Some(&self.source)
898 /// struct SuperErrorSideKick;
900 /// impl fmt::Display for SuperErrorSideKick {
901 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
902 /// write!(f, "SuperErrorSideKick is here!")
906 /// impl Error for SuperErrorSideKick {}
908 /// fn get_super_error() -> Result<(), SuperError> {
909 /// Err(SuperError { source: SuperErrorSideKick })
913 /// match get_super_error() {
914 /// Err(e) => println!("Error: {}", Report::new(e)),
915 /// _ => println!("No error"),
920 /// This example produces the following output:
923 /// Error: SuperError is here!: SuperErrorSideKick is here!
926 /// ## Output consistency
928 /// Report prints the same output via `Display` and `Debug`, so it works well with
929 /// [`Result::unwrap`]/[`Result::expect`] which print their `Err` variant via `Debug`:
932 /// #![feature(error_reporter)]
933 /// use std::error::Report;
934 /// # use std::error::Error;
936 /// # #[derive(Debug)]
937 /// # struct SuperError {
938 /// # source: SuperErrorSideKick,
940 /// # impl fmt::Display for SuperError {
941 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
942 /// # write!(f, "SuperError is here!")
945 /// # impl Error for SuperError {
946 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
947 /// # Some(&self.source)
950 /// # #[derive(Debug)]
951 /// # struct SuperErrorSideKick;
952 /// # impl fmt::Display for SuperErrorSideKick {
953 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954 /// # write!(f, "SuperErrorSideKick is here!")
957 /// # impl Error for SuperErrorSideKick {}
958 /// # fn get_super_error() -> Result<(), SuperError> {
959 /// # Err(SuperError { source: SuperErrorSideKick })
962 /// get_super_error().map_err(Report::new).unwrap();
965 /// This example produces the following output:
968 /// thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: SuperError is here!: SuperErrorSideKick is here!', src/error.rs:34:40
969 /// note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
972 /// ## Return from `main`
974 /// `Report` also implements `From` for all types that implement [`Error`], this when combined with
975 /// the `Debug` output means `Report` is an ideal starting place for formatting errors returned
979 /// #![feature(error_reporter)]
980 /// use std::error::Report;
981 /// # use std::error::Error;
983 /// # #[derive(Debug)]
984 /// # struct SuperError {
985 /// # source: SuperErrorSideKick,
987 /// # impl fmt::Display for SuperError {
988 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989 /// # write!(f, "SuperError is here!")
992 /// # impl Error for SuperError {
993 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
994 /// # Some(&self.source)
997 /// # #[derive(Debug)]
998 /// # struct SuperErrorSideKick;
999 /// # impl fmt::Display for SuperErrorSideKick {
1000 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1001 /// # write!(f, "SuperErrorSideKick is here!")
1004 /// # impl Error for SuperErrorSideKick {}
1005 /// # fn get_super_error() -> Result<(), SuperError> {
1006 /// # Err(SuperError { source: SuperErrorSideKick })
1009 /// fn main() -> Result<(), Report> {
1010 /// get_super_error()?;
1015 /// This example produces the following output:
1018 /// Error: SuperError is here!: SuperErrorSideKick is here!
1021 /// **Note**: `Report`s constructed via `?` and `From` will be configured to use the single line
1022 /// output format, if you want to make sure your `Report`s are pretty printed and include backtrace
1023 /// you will need to manually convert and enable those flags.
1026 /// #![feature(error_reporter)]
1027 /// use std::error::Report;
1028 /// # use std::error::Error;
1030 /// # #[derive(Debug)]
1031 /// # struct SuperError {
1032 /// # source: SuperErrorSideKick,
1034 /// # impl fmt::Display for SuperError {
1035 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1036 /// # write!(f, "SuperError is here!")
1039 /// # impl Error for SuperError {
1040 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1041 /// # Some(&self.source)
1044 /// # #[derive(Debug)]
1045 /// # struct SuperErrorSideKick;
1046 /// # impl fmt::Display for SuperErrorSideKick {
1047 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1048 /// # write!(f, "SuperErrorSideKick is here!")
1051 /// # impl Error for SuperErrorSideKick {}
1052 /// # fn get_super_error() -> Result<(), SuperError> {
1053 /// # Err(SuperError { source: SuperErrorSideKick })
1056 /// fn main() -> Result<(), Report> {
1057 /// get_super_error()
1058 /// .map_err(Report::from)
1059 /// .map_err(|r| r.pretty(true).show_backtrace(true))?;
1064 /// This example produces the following output:
1067 /// Error: SuperError is here!
1070 /// SuperErrorSideKick is here!
1072 #[unstable(feature = "error_reporter", issue = "90172")]
1073 pub struct Report<E = Box<dyn Error>> {
1074 /// The error being reported.
1076 /// Whether a backtrace should be included as part of the report.
1077 show_backtrace: bool,
1078 /// Whether the report should be pretty-printed.
1086 /// Create a new `Report` from an input error.
1087 #[unstable(feature = "error_reporter", issue = "90172")]
1088 pub fn new(error: E) -> Report<E> {
1094 /// Enable pretty-printing the report across multiple lines.
1099 /// #![feature(error_reporter)]
1100 /// use std::error::Report;
1101 /// # use std::error::Error;
1103 /// # #[derive(Debug)]
1104 /// # struct SuperError {
1105 /// # source: SuperErrorSideKick,
1107 /// # impl fmt::Display for SuperError {
1108 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1109 /// # write!(f, "SuperError is here!")
1112 /// # impl Error for SuperError {
1113 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1114 /// # Some(&self.source)
1117 /// # #[derive(Debug)]
1118 /// # struct SuperErrorSideKick;
1119 /// # impl fmt::Display for SuperErrorSideKick {
1120 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1121 /// # write!(f, "SuperErrorSideKick is here!")
1124 /// # impl Error for SuperErrorSideKick {}
1126 /// let error = SuperError { source: SuperErrorSideKick };
1127 /// let report = Report::new(error).pretty(true);
1128 /// eprintln!("Error: {report:?}");
1131 /// This example produces the following output:
1134 /// Error: SuperError is here!
1137 /// SuperErrorSideKick is here!
1140 /// When there are multiple source errors the causes will be numbered in order of iteration
1141 /// starting from the outermost error.
1144 /// #![feature(error_reporter)]
1145 /// use std::error::Report;
1146 /// # use std::error::Error;
1148 /// # #[derive(Debug)]
1149 /// # struct SuperError {
1150 /// # source: SuperErrorSideKick,
1152 /// # impl fmt::Display for SuperError {
1153 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1154 /// # write!(f, "SuperError is here!")
1157 /// # impl Error for SuperError {
1158 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1159 /// # Some(&self.source)
1162 /// # #[derive(Debug)]
1163 /// # struct SuperErrorSideKick {
1164 /// # source: SuperErrorSideKickSideKick,
1166 /// # impl fmt::Display for SuperErrorSideKick {
1167 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1168 /// # write!(f, "SuperErrorSideKick is here!")
1171 /// # impl Error for SuperErrorSideKick {
1172 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1173 /// # Some(&self.source)
1176 /// # #[derive(Debug)]
1177 /// # struct SuperErrorSideKickSideKick;
1178 /// # impl fmt::Display for SuperErrorSideKickSideKick {
1179 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180 /// # write!(f, "SuperErrorSideKickSideKick is here!")
1183 /// # impl Error for SuperErrorSideKickSideKick { }
1185 /// let source = SuperErrorSideKickSideKick;
1186 /// let source = SuperErrorSideKick { source };
1187 /// let error = SuperError { source };
1188 /// let report = Report::new(error).pretty(true);
1189 /// eprintln!("Error: {report:?}");
1192 /// This example produces the following output:
1195 /// Error: SuperError is here!
1198 /// 0: SuperErrorSideKick is here!
1199 /// 1: SuperErrorSideKickSideKick is here!
1201 #[unstable(feature = "error_reporter", issue = "90172")]
1202 pub fn pretty(mut self, pretty: bool) -> Self {
1203 self.pretty = pretty;
1207 /// Display backtrace if available when using pretty output format.
1211 /// **Note**: Report will search for the first `Backtrace` it can find starting from the
1212 /// outermost error. In this example it will display the backtrace from the second error in the
1213 /// chain, `SuperErrorSideKick`.
1216 /// #![feature(error_reporter)]
1217 /// #![feature(backtrace)]
1218 /// # use std::error::Error;
1220 /// use std::error::Report;
1221 /// use std::backtrace::Backtrace;
1223 /// # #[derive(Debug)]
1224 /// # struct SuperError {
1225 /// # source: SuperErrorSideKick,
1227 /// # impl fmt::Display for SuperError {
1228 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229 /// # write!(f, "SuperError is here!")
1232 /// # impl Error for SuperError {
1233 /// # fn source(&self) -> Option<&(dyn Error + 'static)> {
1234 /// # Some(&self.source)
1237 /// #[derive(Debug)]
1238 /// struct SuperErrorSideKick {
1239 /// backtrace: Backtrace,
1242 /// impl SuperErrorSideKick {
1243 /// fn new() -> SuperErrorSideKick {
1244 /// SuperErrorSideKick { backtrace: Backtrace::force_capture() }
1248 /// impl Error for SuperErrorSideKick {
1249 /// fn backtrace(&self) -> Option<&Backtrace> {
1250 /// Some(&self.backtrace)
1254 /// // The rest of the example is unchanged ...
1255 /// # impl fmt::Display for SuperErrorSideKick {
1256 /// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1257 /// # write!(f, "SuperErrorSideKick is here!")
1261 /// let source = SuperErrorSideKick::new();
1262 /// let error = SuperError { source };
1263 /// let report = Report::new(error).pretty(true).show_backtrace(true);
1264 /// eprintln!("Error: {report:?}");
1267 /// This example produces something similar to the following output:
1270 /// Error: SuperError is here!
1273 /// SuperErrorSideKick is here!
1275 /// Stack backtrace:
1276 /// 0: rust_out::main::_doctest_main_src_error_rs_1158_0::SuperErrorSideKick::new
1277 /// 1: rust_out::main::_doctest_main_src_error_rs_1158_0
1278 /// 2: rust_out::main
1279 /// 3: core::ops::function::FnOnce::call_once
1280 /// 4: std::sys_common::backtrace::__rust_begin_short_backtrace
1281 /// 5: std::rt::lang_start::{{closure}}
1282 /// 6: std::panicking::try
1283 /// 7: std::rt::lang_start_internal
1284 /// 8: std::rt::lang_start
1286 /// 10: __libc_start_main
1289 #[unstable(feature = "error_reporter", issue = "90172")]
1290 pub fn show_backtrace(mut self, show_backtrace: bool) -> Self {
1291 self.show_backtrace = show_backtrace;
1300 fn backtrace(&self) -> Option<&Backtrace> {
1301 // have to grab the backtrace on the first error directly since that error may not be
1303 let backtrace = self.error.backtrace();
1304 let backtrace = backtrace.or_else(|| {
1307 .map(|source| source.chain().find_map(|source| source.backtrace()))
1313 /// Format the report as a single line.
1314 #[unstable(feature = "error_reporter", issue = "90172")]
1315 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1316 write!(f, "{}", self.error)?;
1318 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1320 for cause in sources {
1321 write!(f, ": {cause}")?;
1327 /// Format the report as multiple lines, with each error cause on its own line.
1328 #[unstable(feature = "error_reporter", issue = "90172")]
1329 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1330 let error = &self.error;
1332 write!(f, "{error}")?;
1334 if let Some(cause) = error.source() {
1335 write!(f, "\n\nCaused by:")?;
1337 let multiple = cause.source().is_some();
1339 for (ind, error) in cause.chain().enumerate() {
1341 let mut indented = Indented { inner: f };
1343 write!(indented, "{ind: >4}: {error}")?;
1345 write!(indented, " {error}")?;
1350 if self.show_backtrace {
1351 let backtrace = self.backtrace();
1353 if let Some(backtrace) = backtrace {
1354 let backtrace = backtrace.to_string();
1356 f.write_str("\n\nStack backtrace:\n")?;
1357 f.write_str(backtrace.trim_end())?;
1365 impl Report<Box<dyn Error>> {
1366 fn backtrace(&self) -> Option<&Backtrace> {
1367 // have to grab the backtrace on the first error directly since that error may not be
1369 let backtrace = self.error.backtrace();
1370 let backtrace = backtrace.or_else(|| {
1373 .map(|source| source.chain().find_map(|source| source.backtrace()))
1379 /// Format the report as a single line.
1380 #[unstable(feature = "error_reporter", issue = "90172")]
1381 fn fmt_singleline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1382 write!(f, "{}", self.error)?;
1384 let sources = self.error.source().into_iter().flat_map(<dyn Error>::chain);
1386 for cause in sources {
1387 write!(f, ": {cause}")?;
1393 /// Format the report as multiple lines, with each error cause on its own line.
1394 #[unstable(feature = "error_reporter", issue = "90172")]
1395 fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1396 let error = &self.error;
1398 write!(f, "{error}")?;
1400 if let Some(cause) = error.source() {
1401 write!(f, "\n\nCaused by:")?;
1403 let multiple = cause.source().is_some();
1405 for (ind, error) in cause.chain().enumerate() {
1407 let mut indented = Indented { inner: f };
1409 write!(indented, "{ind: >4}: {error}")?;
1411 write!(indented, " {error}")?;
1416 if self.show_backtrace {
1417 let backtrace = self.backtrace();
1419 if let Some(backtrace) = backtrace {
1420 let backtrace = backtrace.to_string();
1422 f.write_str("\n\nStack backtrace:\n")?;
1423 f.write_str(backtrace.trim_end())?;
1431 #[unstable(feature = "error_reporter", issue = "90172")]
1432 impl<E> From<E> for Report<E>
1436 fn from(error: E) -> Self {
1437 Report { error, show_backtrace: false, pretty: false }
1441 #[unstable(feature = "error_reporter", issue = "90172")]
1442 impl<'a, E> From<E> for Report<Box<dyn Error + 'a>>
1446 fn from(error: E) -> Self {
1447 let error = box error;
1448 Report { error, show_backtrace: false, pretty: false }
1452 #[unstable(feature = "error_reporter", issue = "90172")]
1453 impl<E> fmt::Display for Report<E>
1457 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1462 #[unstable(feature = "error_reporter", issue = "90172")]
1463 impl fmt::Display for Report<Box<dyn Error>> {
1464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1465 if self.pretty { self.fmt_multiline(f) } else { self.fmt_singleline(f) }
1469 // This type intentionally outputs the same format for `Display` and `Debug`for
1470 // situations where you unwrap a `Report` or return it from main.
1471 #[unstable(feature = "error_reporter", issue = "90172")]
1472 impl<E> fmt::Debug for Report<E>
1474 Report<E>: fmt::Display,
1476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1477 fmt::Display::fmt(self, f)
1481 /// Wrapper type for indenting the inner source.
1482 struct Indented<'a, D> {
1486 impl<T> Write for Indented<'_, T>
1490 fn write_str(&mut self, s: &str) -> fmt::Result {
1491 for (i, line) in s.split('\n').enumerate() {
1493 self.inner.write_char('\n')?;
1494 self.inner.write_str(" ")?;
1497 self.inner.write_str(line)?;