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.
18 use crate::alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
19 use crate::any::TypeId;
20 use crate::backtrace::Backtrace;
21 use crate::borrow::Cow;
24 use crate::fmt::{self, Debug, Display};
25 use crate::mem::transmute;
30 /// `Error` is a trait representing the basic expectations for error values,
31 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
32 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
33 /// cause chain information:
35 /// The [`source`] method is generally used when errors cross "abstraction
36 /// boundaries". If one module must report an error that is caused by an error
37 /// from a lower-level module, it can allow access to that error via the
38 /// [`source`] method. This makes it possible for the high-level module to
39 /// provide its own errors while also revealing some of the implementation for
40 /// debugging via [`source`] chains.
42 /// [`Result<T, E>`]: ../result/enum.Result.html
43 /// [`Display`]: ../fmt/trait.Display.html
44 /// [`Debug`]: ../fmt/trait.Debug.html
45 /// [`source`]: trait.Error.html#method.source
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub trait Error: Debug + Display {
48 /// **This method is soft-deprecated.**
50 /// Although using it won’t cause compilation warning,
51 /// new code should use [`Display`] instead
52 /// and new `impl`s can omit it.
54 /// To obtain error description as a string, use `to_string()`.
56 /// [`Display`]: ../fmt/trait.Display.html
61 /// match "xc".parse::<u32>() {
63 /// // Print `e` itself, not `e.description()`.
64 /// println!("Error: {}", e);
66 /// _ => println!("No error"),
69 #[stable(feature = "rust1", since = "1.0.0")]
70 fn description(&self) -> &str {
71 "description() is deprecated; use Display"
74 /// The lower-level cause of this error, if any.
79 /// use std::error::Error;
83 /// struct SuperError {
84 /// side: SuperErrorSideKick,
87 /// impl fmt::Display for SuperError {
88 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 /// write!(f, "SuperError is here!")
93 /// impl Error for SuperError {
94 /// fn description(&self) -> &str {
95 /// "I'm the superhero of errors"
98 /// fn cause(&self) -> Option<&dyn Error> {
104 /// struct SuperErrorSideKick;
106 /// impl fmt::Display for SuperErrorSideKick {
107 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 /// write!(f, "SuperErrorSideKick is here!")
112 /// impl Error for SuperErrorSideKick {
113 /// fn description(&self) -> &str {
114 /// "I'm SuperError side kick"
118 /// fn get_super_error() -> Result<(), SuperError> {
119 /// Err(SuperError { side: SuperErrorSideKick })
123 /// match get_super_error() {
125 /// println!("Error: {}", e.description());
126 /// println!("Caused by: {}", e.cause().unwrap());
128 /// _ => println!("No error"),
132 #[stable(feature = "rust1", since = "1.0.0")]
133 #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
135 fn cause(&self) -> Option<&dyn Error> {
139 /// The lower-level source of this error, if any.
144 /// use std::error::Error;
148 /// struct SuperError {
149 /// side: SuperErrorSideKick,
152 /// impl fmt::Display for SuperError {
153 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154 /// write!(f, "SuperError is here!")
158 /// impl Error for SuperError {
159 /// fn description(&self) -> &str {
160 /// "I'm the superhero of errors"
163 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
169 /// struct SuperErrorSideKick;
171 /// impl fmt::Display for SuperErrorSideKick {
172 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 /// write!(f, "SuperErrorSideKick is here!")
177 /// impl Error for SuperErrorSideKick {
178 /// fn description(&self) -> &str {
179 /// "I'm SuperError side kick"
183 /// fn get_super_error() -> Result<(), SuperError> {
184 /// Err(SuperError { side: SuperErrorSideKick })
188 /// match get_super_error() {
190 /// println!("Error: {}", e.description());
191 /// println!("Caused by: {}", e.source().unwrap());
193 /// _ => println!("No error"),
197 #[stable(feature = "error_source", since = "1.30.0")]
198 fn source(&self) -> Option<&(dyn Error + 'static)> { None }
200 /// Gets the `TypeId` of `self`.
202 #[unstable(feature = "error_type_id",
203 reason = "this is memory-unsafe to override in user code",
205 fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
209 /// Returns a stack backtrace, if available, of where this error ocurred.
211 /// This function allows inspecting the location, in code, of where an error
212 /// happened. The returned `Backtrace` contains information about the stack
213 /// trace of the OS thread of execution of where the error originated from.
215 /// Note that not all errors contain a `Backtrace`. Also note that a
216 /// `Backtrace` may actually be empty. For more information consult the
217 /// `Backtrace` type itself.
218 #[unstable(feature = "backtrace", issue = "53487")]
219 fn backtrace(&self) -> Option<&Backtrace> {
225 // This is a hack to prevent `type_id` from being overridden by `Error`
226 // implementations, since that can enable unsound downcasting.
227 #[unstable(feature = "error_type_id", issue = "60784")]
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
234 /// Converts a type of [`Error`] into a box of dyn [`Error`].
236 /// [`Error`]: ../error/trait.Error.html
241 /// use std::error::Error;
248 /// impl fmt::Display for AnError {
249 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250 /// write!(f , "An error")
254 /// impl Error for AnError {
255 /// fn description(&self) -> &str {
256 /// "Description of an error"
260 /// let an_error = AnError;
261 /// assert!(0 == mem::size_of_val(&an_error));
262 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
263 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
265 fn from(err: E) -> Box<dyn Error + 'a> {
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
272 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
273 /// dyn [`Error`] + [`Send`] + [`Sync`].
275 /// [`Error`]: ../error/trait.Error.html
280 /// use std::error::Error;
287 /// impl fmt::Display for AnError {
288 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 /// write!(f , "An error")
293 /// impl Error for AnError {
294 /// fn description(&self) -> &str {
295 /// "Description of an error"
299 /// unsafe impl Send for AnError {}
301 /// unsafe impl Sync for AnError {}
303 /// let an_error = AnError;
304 /// assert!(0 == mem::size_of_val(&an_error));
305 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
307 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
309 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl From<String> for Box<dyn Error + Send + Sync> {
316 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
318 /// [`Error`]: ../error/trait.Error.html
323 /// use std::error::Error;
326 /// let a_string_error = "a string error".to_string();
327 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
329 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
331 fn from(err: String) -> Box<dyn Error + Send + Sync> {
332 struct StringError(String);
334 impl Error for StringError {
335 fn description(&self) -> &str { &self.0 }
338 impl Display for StringError {
339 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340 Display::fmt(&self.0, f)
344 // Purposefully skip printing "StringError(..)"
345 impl Debug for StringError {
346 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347 Debug::fmt(&self.0, f)
351 Box::new(StringError(err))
355 #[stable(feature = "string_box_error", since = "1.6.0")]
356 impl From<String> for Box<dyn Error> {
357 /// Converts a [`String`] into a box of dyn [`Error`].
359 /// [`Error`]: ../error/trait.Error.html
364 /// use std::error::Error;
367 /// let a_string_error = "a string error".to_string();
368 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
369 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
371 fn from(str_err: String) -> Box<dyn Error> {
372 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
373 let err2: Box<dyn Error> = err1;
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
380 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
382 /// [`Error`]: ../error/trait.Error.html
387 /// use std::error::Error;
390 /// let a_str_error = "a str error";
391 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
393 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
395 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
396 From::from(String::from(err))
400 #[stable(feature = "string_box_error", since = "1.6.0")]
401 impl From<&str> for Box<dyn Error> {
402 /// Converts a [`str`] into a box of dyn [`Error`].
404 /// [`Error`]: ../error/trait.Error.html
409 /// use std::error::Error;
412 /// let a_str_error = "a str error";
413 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
414 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
416 fn from(err: &str) -> Box<dyn Error> {
417 From::from(String::from(err))
421 #[stable(feature = "cow_box_error", since = "1.22.0")]
422 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
423 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
425 /// [`Cow`]: ../borrow/enum.Cow.html
426 /// [`Error`]: ../error/trait.Error.html
431 /// use std::error::Error;
433 /// use std::borrow::Cow;
435 /// let a_cow_str_error = Cow::from("a str error");
436 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
438 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
440 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
441 From::from(String::from(err))
445 #[stable(feature = "cow_box_error", since = "1.22.0")]
446 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
447 /// Converts a [`Cow`] into a box of dyn [`Error`].
449 /// [`Cow`]: ../borrow/enum.Cow.html
450 /// [`Error`]: ../error/trait.Error.html
455 /// use std::error::Error;
457 /// use std::borrow::Cow;
459 /// let a_cow_str_error = Cow::from("a str error");
460 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
461 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
463 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
464 From::from(String::from(err))
468 #[stable(feature = "never_type", since = "1.41.0")]
470 fn description(&self) -> &str { *self }
473 #[unstable(feature = "allocator_api",
474 reason = "the precise API and guarantees it provides may be tweaked.",
476 impl Error for AllocErr {
477 fn description(&self) -> &str {
478 "memory allocation failed"
482 #[unstable(feature = "allocator_api",
483 reason = "the precise API and guarantees it provides may be tweaked.",
485 impl Error for LayoutErr {
486 fn description(&self) -> &str {
487 "invalid parameters to Layout::from_size_align"
491 #[unstable(feature = "allocator_api",
492 reason = "the precise API and guarantees it provides may be tweaked.",
494 impl Error for CannotReallocInPlace {
495 fn description(&self) -> &str {
496 CannotReallocInPlace::description(self)
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl Error for str::ParseBoolError {
502 fn description(&self) -> &str { "failed to parse bool" }
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl Error for str::Utf8Error {
507 fn description(&self) -> &str {
508 "invalid utf-8: corrupt contents"
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Error for num::ParseIntError {
514 fn description(&self) -> &str {
519 #[stable(feature = "try_from", since = "1.34.0")]
520 impl Error for num::TryFromIntError {
521 fn description(&self) -> &str {
526 #[stable(feature = "try_from", since = "1.34.0")]
527 impl Error for array::TryFromSliceError {
528 fn description(&self) -> &str {
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl Error for num::ParseFloatError {
535 fn description(&self) -> &str {
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl Error for string::FromUtf8Error {
542 fn description(&self) -> &str {
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl Error for string::FromUtf16Error {
549 fn description(&self) -> &str {
554 #[stable(feature = "decode_utf16", since = "1.9.0")]
555 impl Error for char::DecodeUtf16Error {
556 fn description(&self) -> &str {
557 "unpaired surrogate found"
561 #[stable(feature = "box_error", since = "1.8.0")]
562 impl<T: Error> Error for Box<T> {
563 fn description(&self) -> &str {
564 Error::description(&**self)
568 fn cause(&self) -> Option<&dyn Error> {
569 Error::cause(&**self)
572 fn source(&self) -> Option<&(dyn Error + 'static)> {
573 Error::source(&**self)
577 #[stable(feature = "fmt_error", since = "1.11.0")]
578 impl Error for fmt::Error {
579 fn description(&self) -> &str {
580 "an error occurred when formatting an argument"
584 #[stable(feature = "try_borrow", since = "1.13.0")]
585 impl Error for cell::BorrowError {
586 fn description(&self) -> &str {
587 "already mutably borrowed"
591 #[stable(feature = "try_borrow", since = "1.13.0")]
592 impl Error for cell::BorrowMutError {
593 fn description(&self) -> &str {
598 #[stable(feature = "try_from", since = "1.34.0")]
599 impl Error for char::CharTryFromError {
600 fn description(&self) -> &str {
601 "converted integer out of range for `char`"
605 #[stable(feature = "char_from_str", since = "1.20.0")]
606 impl Error for char::ParseCharError {
607 fn description(&self) -> &str {
612 // Copied from `any.rs`.
613 impl dyn Error + 'static {
614 /// Returns `true` if the boxed type is the same as `T`
615 #[stable(feature = "error_downcast", since = "1.3.0")]
617 pub fn is<T: Error + 'static>(&self) -> bool {
618 // Get `TypeId` of the type this function is instantiated with.
619 let t = TypeId::of::<T>();
621 // Get `TypeId` of the type in the trait object.
622 let boxed = self.type_id(private::Internal);
624 // Compare both `TypeId`s on equality.
628 /// Returns some reference to the boxed value if it is of type `T`, or
629 /// `None` if it isn't.
630 #[stable(feature = "error_downcast", since = "1.3.0")]
632 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
635 Some(&*(self as *const dyn Error as *const T))
642 /// Returns some mutable reference to the boxed value if it is of type `T`, or
643 /// `None` if it isn't.
644 #[stable(feature = "error_downcast", since = "1.3.0")]
646 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
649 Some(&mut *(self as *mut dyn Error as *mut T))
657 impl dyn Error + 'static + Send {
658 /// Forwards to the method defined on the type `dyn Error`.
659 #[stable(feature = "error_downcast", since = "1.3.0")]
661 pub fn is<T: Error + 'static>(&self) -> bool {
662 <dyn Error + 'static>::is::<T>(self)
665 /// Forwards to the method defined on the type `dyn Error`.
666 #[stable(feature = "error_downcast", since = "1.3.0")]
668 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
669 <dyn Error + 'static>::downcast_ref::<T>(self)
672 /// Forwards to the method defined on the type `dyn Error`.
673 #[stable(feature = "error_downcast", since = "1.3.0")]
675 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
676 <dyn Error + 'static>::downcast_mut::<T>(self)
680 impl dyn Error + 'static + Send + Sync {
681 /// Forwards to the method defined on the type `dyn Error`.
682 #[stable(feature = "error_downcast", since = "1.3.0")]
684 pub fn is<T: Error + 'static>(&self) -> bool {
685 <dyn Error + 'static>::is::<T>(self)
688 /// Forwards to the method defined on the type `dyn Error`.
689 #[stable(feature = "error_downcast", since = "1.3.0")]
691 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
692 <dyn Error + 'static>::downcast_ref::<T>(self)
695 /// Forwards to the method defined on the type `dyn Error`.
696 #[stable(feature = "error_downcast", since = "1.3.0")]
698 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
699 <dyn Error + 'static>::downcast_mut::<T>(self)
705 #[stable(feature = "error_downcast", since = "1.3.0")]
706 /// Attempts to downcast the box to a concrete type.
707 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
710 let raw: *mut dyn Error = Box::into_raw(self);
711 Ok(Box::from_raw(raw as *mut T))
718 /// Returns an iterator starting with the current error and continuing with
719 /// recursively calling [`source`].
721 /// If you want to omit the current error and only use its sources,
727 /// #![feature(error_iter)]
728 /// use std::error::Error;
735 /// struct B(Option<Box<dyn Error + 'static>>);
737 /// impl fmt::Display for A {
738 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
743 /// impl fmt::Display for B {
744 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
749 /// impl Error for A {}
751 /// impl Error for B {
752 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
753 /// self.0.as_ref().map(|e| e.as_ref())
757 /// let b = B(Some(Box::new(A)));
759 /// // let err : Box<Error> = b.into(); // or
760 /// let err = &b as &(dyn Error);
762 /// let mut iter = err.chain();
764 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
765 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
766 /// assert!(iter.next().is_none());
767 /// assert!(iter.next().is_none());
770 /// [`source`]: trait.Error.html#method.source
771 #[unstable(feature = "error_iter", issue = "58520")]
773 pub fn chain(&self) -> Chain<'_> {
780 /// An iterator over an [`Error`] and its sources.
782 /// If you want to omit the initial error and only process
783 /// its sources, use `skip(1)`.
785 /// [`Error`]: trait.Error.html
786 #[unstable(feature = "error_iter", issue = "58520")]
787 #[derive(Clone, Debug)]
788 pub struct Chain<'a> {
789 current: Option<&'a (dyn Error + 'static)>,
792 #[unstable(feature = "error_iter", issue = "58520")]
793 impl<'a> Iterator for Chain<'a> {
794 type Item = &'a (dyn Error + 'static);
796 fn next(&mut self) -> Option<Self::Item> {
797 let current = self.current;
798 self.current = self.current.and_then(Error::source);
803 impl dyn Error + Send {
805 #[stable(feature = "error_downcast", since = "1.3.0")]
806 /// Attempts to downcast the box to a concrete type.
807 pub fn downcast<T: Error + 'static>(self: Box<Self>)
808 -> Result<Box<T>, Box<dyn Error + Send>> {
809 let err: Box<dyn Error> = self;
810 <dyn Error>::downcast(err).map_err(|s| unsafe {
811 // Reapply the `Send` marker.
812 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
817 impl dyn Error + Send + Sync {
819 #[stable(feature = "error_downcast", since = "1.3.0")]
820 /// Attempts to downcast the box to a concrete type.
821 pub fn downcast<T: Error + 'static>(self: Box<Self>)
822 -> Result<Box<T>, Box<Self>> {
823 let err: Box<dyn Error> = self;
824 <dyn Error>::downcast(err).map_err(|s| unsafe {
825 // Reapply the `Send + Sync` marker.
826 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
836 #[derive(Debug, PartialEq)]
838 #[derive(Debug, PartialEq)]
841 impl fmt::Display for A {
842 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
846 impl fmt::Display for B {
847 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
853 fn description(&self) -> &str { "A-desc" }
856 fn description(&self) -> &str { "A-desc" }
862 let a = &mut a as &mut (dyn Error + 'static);
863 assert_eq!(a.downcast_ref::<A>(), Some(&A));
864 assert_eq!(a.downcast_ref::<B>(), None);
865 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
866 assert_eq!(a.downcast_mut::<B>(), None);
868 let a: Box<dyn Error> = Box::new(A);
869 match a.downcast::<B>() {
870 Ok(..) => panic!("expected error"),
871 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),