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::borrow::Cow;
23 use crate::fmt::{self, Debug, Display};
24 use crate::mem::transmute;
29 /// `Error` is a trait representing the basic expectations for error values,
30 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
31 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
32 /// cause chain information:
34 /// The [`source`] method is generally used when errors cross "abstraction
35 /// boundaries". If one module must report an error that is caused by an error
36 /// from a lower-level module, it can allow access to that error via the
37 /// [`source`] method. This makes it possible for the high-level module to
38 /// provide its own errors while also revealing some of the implementation for
39 /// debugging via [`source`] chains.
41 /// [`Result<T, E>`]: ../result/enum.Result.html
42 /// [`Display`]: ../fmt/trait.Display.html
43 /// [`Debug`]: ../fmt/trait.Debug.html
44 /// [`source`]: trait.Error.html#method.source
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait Error: Debug + Display {
47 /// **This method is soft-deprecated.**
49 /// Although using it won’t cause compilation warning,
50 /// new code should use [`Display`] instead
51 /// and new `impl`s can omit it.
53 /// To obtain error description as a string, use `to_string()`.
55 /// [`Display`]: ../fmt/trait.Display.html
60 /// match "xc".parse::<u32>() {
62 /// // Print `e` itself, not `e.description()`.
63 /// println!("Error: {}", e);
65 /// _ => println!("No error"),
68 #[stable(feature = "rust1", since = "1.0.0")]
69 fn description(&self) -> &str {
70 "description() is deprecated; use Display"
73 /// The lower-level cause of this error, if any.
78 /// use std::error::Error;
82 /// struct SuperError {
83 /// side: SuperErrorSideKick,
86 /// impl fmt::Display for SuperError {
87 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 /// write!(f, "SuperError is here!")
92 /// impl Error for SuperError {
93 /// fn description(&self) -> &str {
94 /// "I'm the superhero of errors"
97 /// fn cause(&self) -> Option<&Error> {
103 /// struct SuperErrorSideKick;
105 /// impl fmt::Display for SuperErrorSideKick {
106 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 /// write!(f, "SuperErrorSideKick is here!")
111 /// impl Error for SuperErrorSideKick {
112 /// fn description(&self) -> &str {
113 /// "I'm SuperError side kick"
117 /// fn get_super_error() -> Result<(), SuperError> {
118 /// Err(SuperError { side: SuperErrorSideKick })
122 /// match get_super_error() {
124 /// println!("Error: {}", e.description());
125 /// println!("Caused by: {}", e.cause().unwrap());
127 /// _ => println!("No error"),
131 #[stable(feature = "rust1", since = "1.0.0")]
132 #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
134 fn cause(&self) -> Option<&dyn Error> {
138 /// The lower-level source of this error, if any.
143 /// use std::error::Error;
147 /// struct SuperError {
148 /// side: SuperErrorSideKick,
151 /// impl fmt::Display for SuperError {
152 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 /// write!(f, "SuperError is here!")
157 /// impl Error for SuperError {
158 /// fn description(&self) -> &str {
159 /// "I'm the superhero of errors"
162 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
168 /// struct SuperErrorSideKick;
170 /// impl fmt::Display for SuperErrorSideKick {
171 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172 /// write!(f, "SuperErrorSideKick is here!")
176 /// impl Error for SuperErrorSideKick {
177 /// fn description(&self) -> &str {
178 /// "I'm SuperError side kick"
182 /// fn get_super_error() -> Result<(), SuperError> {
183 /// Err(SuperError { side: SuperErrorSideKick })
187 /// match get_super_error() {
189 /// println!("Error: {}", e.description());
190 /// println!("Caused by: {}", e.source().unwrap());
192 /// _ => println!("No error"),
196 #[stable(feature = "error_source", since = "1.30.0")]
197 fn source(&self) -> Option<&(dyn Error + 'static)> { None }
199 /// Gets the `TypeId` of `self`
201 #[unstable(feature = "error_type_id",
202 reason = "this is memory unsafe to override in user code",
204 fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
210 // This is a hack to prevent `type_id` from being overridden by `Error`
211 // implementations, since that can enable unsound downcasting.
212 #[unstable(feature = "error_type_id", issue = "60784")]
217 #[stable(feature = "rust1", since = "1.0.0")]
218 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
219 /// Converts a type of [`Error`] into a box of dyn [`Error`].
221 /// [`Error`]: ../error/trait.Error.html
226 /// use std::error::Error;
233 /// impl fmt::Display for AnError {
234 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235 /// write!(f , "An error")
239 /// impl Error for AnError {
240 /// fn description(&self) -> &str {
241 /// "Description of an error"
245 /// let an_error = AnError;
246 /// assert!(0 == mem::size_of_val(&an_error));
247 /// let a_boxed_error = Box::<Error>::from(an_error);
248 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
250 fn from(err: E) -> Box<dyn Error + 'a> {
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
257 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
258 /// [`Send`] + [`Sync`].
260 /// [`Error`]: ../error/trait.Error.html
265 /// use std::error::Error;
272 /// impl fmt::Display for AnError {
273 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274 /// write!(f , "An error")
278 /// impl Error for AnError {
279 /// fn description(&self) -> &str {
280 /// "Description of an error"
284 /// unsafe impl Send for AnError {}
286 /// unsafe impl Sync for AnError {}
288 /// let an_error = AnError;
289 /// assert!(0 == mem::size_of_val(&an_error));
290 /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
292 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
294 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl From<String> for Box<dyn Error + Send + Sync> {
301 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
303 /// [`Error`]: ../error/trait.Error.html
308 /// use std::error::Error;
311 /// let a_string_error = "a string error".to_string();
312 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
314 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
316 fn from(err: String) -> Box<dyn Error + Send + Sync> {
318 struct StringError(String);
320 impl Error for StringError {
321 fn description(&self) -> &str { &self.0 }
324 impl Display for StringError {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 Display::fmt(&self.0, f)
330 Box::new(StringError(err))
334 #[stable(feature = "string_box_error", since = "1.6.0")]
335 impl From<String> for Box<dyn Error> {
336 /// Converts a [`String`] into a box of dyn [`Error`].
338 /// [`Error`]: ../error/trait.Error.html
343 /// use std::error::Error;
346 /// let a_string_error = "a string error".to_string();
347 /// let a_boxed_error = Box::<Error>::from(a_string_error);
348 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
350 fn from(str_err: String) -> Box<dyn Error> {
351 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
352 let err2: Box<dyn Error> = err1;
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
359 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
361 /// [`Error`]: ../error/trait.Error.html
366 /// use std::error::Error;
369 /// let a_str_error = "a str error";
370 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
372 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
374 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
375 From::from(String::from(err))
379 #[stable(feature = "string_box_error", since = "1.6.0")]
380 impl From<&str> for Box<dyn Error> {
381 /// Converts a [`str`] into a box of dyn [`Error`].
383 /// [`Error`]: ../error/trait.Error.html
388 /// use std::error::Error;
391 /// let a_str_error = "a str error";
392 /// let a_boxed_error = Box::<Error>::from(a_str_error);
393 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
395 fn from(err: &str) -> Box<dyn Error> {
396 From::from(String::from(err))
400 #[stable(feature = "cow_box_error", since = "1.22.0")]
401 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
402 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
404 /// [`Cow`]: ../borrow/enum.Cow.html
405 /// [`Error`]: ../error/trait.Error.html
410 /// use std::error::Error;
412 /// use std::borrow::Cow;
414 /// let a_cow_str_error = Cow::from("a str error");
415 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
417 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
419 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
420 From::from(String::from(err))
424 #[stable(feature = "cow_box_error", since = "1.22.0")]
425 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
426 /// Converts a [`Cow`] into a box of dyn [`Error`].
428 /// [`Cow`]: ../borrow/enum.Cow.html
429 /// [`Error`]: ../error/trait.Error.html
434 /// use std::error::Error;
436 /// use std::borrow::Cow;
438 /// let a_cow_str_error = Cow::from("a str error");
439 /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
440 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
442 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
443 From::from(String::from(err))
447 #[unstable(feature = "never_type", issue = "35121")]
449 fn description(&self) -> &str { *self }
452 #[unstable(feature = "allocator_api",
453 reason = "the precise API and guarantees it provides may be tweaked.",
455 impl Error for AllocErr {
456 fn description(&self) -> &str {
457 "memory allocation failed"
461 #[unstable(feature = "allocator_api",
462 reason = "the precise API and guarantees it provides may be tweaked.",
464 impl Error for LayoutErr {
465 fn description(&self) -> &str {
466 "invalid parameters to Layout::from_size_align"
470 #[unstable(feature = "allocator_api",
471 reason = "the precise API and guarantees it provides may be tweaked.",
473 impl Error for CannotReallocInPlace {
474 fn description(&self) -> &str {
475 CannotReallocInPlace::description(self)
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl Error for str::ParseBoolError {
481 fn description(&self) -> &str { "failed to parse bool" }
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl Error for str::Utf8Error {
486 fn description(&self) -> &str {
487 "invalid utf-8: corrupt contents"
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl Error for num::ParseIntError {
493 fn description(&self) -> &str {
498 #[stable(feature = "try_from", since = "1.34.0")]
499 impl Error for num::TryFromIntError {
500 fn description(&self) -> &str {
505 #[stable(feature = "try_from", since = "1.34.0")]
506 impl Error for array::TryFromSliceError {
507 fn description(&self) -> &str {
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Error for num::ParseFloatError {
514 fn description(&self) -> &str {
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl Error for string::FromUtf8Error {
521 fn description(&self) -> &str {
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl Error for string::FromUtf16Error {
528 fn description(&self) -> &str {
533 #[stable(feature = "str_parse_error2", since = "1.8.0")]
534 impl Error for string::ParseError {
535 fn description(&self) -> &str {
540 #[stable(feature = "decode_utf16", since = "1.9.0")]
541 impl Error for char::DecodeUtf16Error {
542 fn description(&self) -> &str {
543 "unpaired surrogate found"
547 #[stable(feature = "box_error", since = "1.8.0")]
548 impl<T: Error> Error for Box<T> {
549 fn description(&self) -> &str {
550 Error::description(&**self)
554 fn cause(&self) -> Option<&dyn Error> {
555 Error::cause(&**self)
559 #[stable(feature = "fmt_error", since = "1.11.0")]
560 impl Error for fmt::Error {
561 fn description(&self) -> &str {
562 "an error occurred when formatting an argument"
566 #[stable(feature = "try_borrow", since = "1.13.0")]
567 impl Error for cell::BorrowError {
568 fn description(&self) -> &str {
569 "already mutably borrowed"
573 #[stable(feature = "try_borrow", since = "1.13.0")]
574 impl Error for cell::BorrowMutError {
575 fn description(&self) -> &str {
580 #[stable(feature = "try_from", since = "1.34.0")]
581 impl Error for char::CharTryFromError {
582 fn description(&self) -> &str {
583 "converted integer out of range for `char`"
587 #[stable(feature = "char_from_str", since = "1.20.0")]
588 impl Error for char::ParseCharError {
589 fn description(&self) -> &str {
594 // copied from any.rs
595 impl dyn Error + 'static {
596 /// Returns `true` if the boxed type is the same as `T`
597 #[stable(feature = "error_downcast", since = "1.3.0")]
599 pub fn is<T: Error + 'static>(&self) -> bool {
600 // Get TypeId of the type this function is instantiated with
601 let t = TypeId::of::<T>();
603 // Get TypeId of the type in the trait object
604 let boxed = self.type_id(private::Internal);
606 // Compare both TypeIds on equality
610 /// Returns some reference to the boxed value if it is of type `T`, or
611 /// `None` if it isn't.
612 #[stable(feature = "error_downcast", since = "1.3.0")]
614 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
617 Some(&*(self as *const dyn Error as *const T))
624 /// Returns some mutable reference to the boxed value if it is of type `T`, or
625 /// `None` if it isn't.
626 #[stable(feature = "error_downcast", since = "1.3.0")]
628 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
631 Some(&mut *(self as *mut dyn Error as *mut T))
639 impl dyn Error + 'static + Send {
640 /// Forwards to the method defined on the type `Any`.
641 #[stable(feature = "error_downcast", since = "1.3.0")]
643 pub fn is<T: Error + 'static>(&self) -> bool {
644 <dyn Error + 'static>::is::<T>(self)
647 /// Forwards to the method defined on the type `Any`.
648 #[stable(feature = "error_downcast", since = "1.3.0")]
650 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
651 <dyn Error + 'static>::downcast_ref::<T>(self)
654 /// Forwards to the method defined on the type `Any`.
655 #[stable(feature = "error_downcast", since = "1.3.0")]
657 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
658 <dyn Error + 'static>::downcast_mut::<T>(self)
662 impl dyn Error + 'static + Send + Sync {
663 /// Forwards to the method defined on the type `Any`.
664 #[stable(feature = "error_downcast", since = "1.3.0")]
666 pub fn is<T: Error + 'static>(&self) -> bool {
667 <dyn Error + 'static>::is::<T>(self)
670 /// Forwards to the method defined on the type `Any`.
671 #[stable(feature = "error_downcast", since = "1.3.0")]
673 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
674 <dyn Error + 'static>::downcast_ref::<T>(self)
677 /// Forwards to the method defined on the type `Any`.
678 #[stable(feature = "error_downcast", since = "1.3.0")]
680 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
681 <dyn Error + 'static>::downcast_mut::<T>(self)
687 #[stable(feature = "error_downcast", since = "1.3.0")]
688 /// Attempt to downcast the box to a concrete type.
689 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
692 let raw: *mut dyn Error = Box::into_raw(self);
693 Ok(Box::from_raw(raw as *mut T))
700 /// Returns an iterator starting with the current error and continuing with
701 /// recursively calling [`source`].
706 /// #![feature(error_iter)]
707 /// use std::error::Error;
714 /// struct B(Option<Box<dyn Error + 'static>>);
716 /// impl fmt::Display for A {
717 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722 /// impl fmt::Display for B {
723 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
728 /// impl Error for A {}
730 /// impl Error for B {
731 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
732 /// self.0.as_ref().map(|e| e.as_ref())
736 /// let b = B(Some(Box::new(A)));
738 /// // let err : Box<Error> = b.into(); // or
739 /// let err = &b as &(dyn Error);
741 /// let mut iter = err.iter_chain();
743 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
744 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
745 /// assert!(iter.next().is_none());
746 /// assert!(iter.next().is_none());
749 /// [`source`]: trait.Error.html#method.source
750 #[unstable(feature = "error_iter", issue = "58520")]
752 pub fn iter_chain(&self) -> ErrorIter<'_> {
758 /// Returns an iterator starting with the [`source`] of this error
759 /// and continuing with recursively calling [`source`].
764 /// #![feature(error_iter)]
765 /// use std::error::Error;
772 /// struct B(Option<Box<dyn Error + 'static>>);
775 /// struct C(Option<Box<dyn Error + 'static>>);
777 /// impl fmt::Display for A {
778 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
783 /// impl fmt::Display for B {
784 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
789 /// impl fmt::Display for C {
790 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795 /// impl Error for A {}
797 /// impl Error for B {
798 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
799 /// self.0.as_ref().map(|e| e.as_ref())
803 /// impl Error for C {
804 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
805 /// self.0.as_ref().map(|e| e.as_ref())
809 /// let b = B(Some(Box::new(A)));
810 /// let c = C(Some(Box::new(b)));
812 /// // let err : Box<Error> = c.into(); // or
813 /// let err = &c as &(dyn Error);
815 /// let mut iter = err.iter_sources();
817 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
818 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
819 /// assert!(iter.next().is_none());
820 /// assert!(iter.next().is_none());
823 /// [`source`]: trait.Error.html#method.source
825 #[unstable(feature = "error_iter", issue = "58520")]
826 pub fn iter_sources(&self) -> ErrorIter<'_> {
828 current: self.source(),
833 /// An iterator over [`Error`]
835 /// [`Error`]: trait.Error.html
836 #[unstable(feature = "error_iter", issue = "58520")]
837 #[derive(Copy, Clone, Debug)]
838 pub struct ErrorIter<'a> {
839 current: Option<&'a (dyn Error + 'static)>,
842 #[unstable(feature = "error_iter", issue = "58520")]
843 impl<'a> Iterator for ErrorIter<'a> {
844 type Item = &'a (dyn Error + 'static);
846 fn next(&mut self) -> Option<Self::Item> {
847 let current = self.current;
848 self.current = self.current.and_then(Error::source);
853 impl dyn Error + Send {
855 #[stable(feature = "error_downcast", since = "1.3.0")]
856 /// Attempt to downcast the box to a concrete type.
857 pub fn downcast<T: Error + 'static>(self: Box<Self>)
858 -> Result<Box<T>, Box<dyn Error + Send>> {
859 let err: Box<dyn Error> = self;
860 <dyn Error>::downcast(err).map_err(|s| unsafe {
861 // reapply the Send marker
862 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
867 impl dyn Error + Send + Sync {
869 #[stable(feature = "error_downcast", since = "1.3.0")]
870 /// Attempt to downcast the box to a concrete type.
871 pub fn downcast<T: Error + 'static>(self: Box<Self>)
872 -> Result<Box<T>, Box<Self>> {
873 let err: Box<dyn Error> = self;
874 <dyn Error>::downcast(err).map_err(|s| unsafe {
875 // reapply the Send+Sync marker
876 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
886 #[derive(Debug, PartialEq)]
888 #[derive(Debug, PartialEq)]
891 impl fmt::Display for A {
892 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
896 impl fmt::Display for B {
897 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 fn description(&self) -> &str { "A-desc" }
906 fn description(&self) -> &str { "A-desc" }
912 let a = &mut a as &mut (dyn Error + 'static);
913 assert_eq!(a.downcast_ref::<A>(), Some(&A));
914 assert_eq!(a.downcast_ref::<B>(), None);
915 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
916 assert_eq!(a.downcast_mut::<B>(), None);
918 let a: Box<dyn Error> = Box::new(A);
919 match a.downcast::<B>() {
920 Ok(..) => panic!("expected error"),
921 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),