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) -> TypeId where Self: 'static {
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
211 /// Converts a type of [`Error`] into a box of dyn [`Error`].
216 /// use std::error::Error;
223 /// impl fmt::Display for AnError {
224 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 /// write!(f , "An error")
229 /// impl Error for AnError {
230 /// fn description(&self) -> &str {
231 /// "Description of an error"
235 /// let an_error = AnError;
236 /// assert!(0 == mem::size_of_val(&an_error));
237 /// let a_boxed_error = Box::<Error>::from(an_error);
238 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
240 fn from(err: E) -> Box<dyn Error + 'a> {
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
247 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
248 /// [`Send`] + [`Sync`].
253 /// use std::error::Error;
260 /// impl fmt::Display for AnError {
261 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 /// write!(f , "An error")
266 /// impl Error for AnError {
267 /// fn description(&self) -> &str {
268 /// "Description of an error"
272 /// unsafe impl Send for AnError {}
274 /// unsafe impl Sync for AnError {}
276 /// let an_error = AnError;
277 /// assert!(0 == mem::size_of_val(&an_error));
278 /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
280 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
282 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl From<String> for Box<dyn Error + Send + Sync> {
289 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
294 /// use std::error::Error;
297 /// let a_string_error = "a string error".to_string();
298 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
300 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
302 fn from(err: String) -> Box<dyn Error + Send + Sync> {
303 struct StringError(String);
305 impl Error for StringError {
306 fn description(&self) -> &str { &self.0 }
309 impl Display for StringError {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 Display::fmt(&self.0, f)
315 // Purposefully skip printing "StringError(..)"
316 impl Debug for StringError {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 Debug::fmt(&self.0, f)
322 Box::new(StringError(err))
326 #[stable(feature = "string_box_error", since = "1.6.0")]
327 impl From<String> for Box<dyn Error> {
328 /// Converts a [`String`] into a box of dyn [`Error`].
333 /// use std::error::Error;
336 /// let a_string_error = "a string error".to_string();
337 /// let a_boxed_error = Box::<Error>::from(a_string_error);
338 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
340 fn from(str_err: String) -> Box<dyn Error> {
341 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
342 let err2: Box<dyn Error> = err1;
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
349 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
354 /// use std::error::Error;
357 /// let a_str_error = "a str error";
358 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
360 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
362 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
363 From::from(String::from(err))
367 #[stable(feature = "string_box_error", since = "1.6.0")]
368 impl From<&str> for Box<dyn Error> {
369 /// Converts a [`str`] into a box of dyn [`Error`].
374 /// use std::error::Error;
377 /// let a_str_error = "a str error";
378 /// let a_boxed_error = Box::<Error>::from(a_str_error);
379 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
381 fn from(err: &str) -> Box<dyn Error> {
382 From::from(String::from(err))
386 #[stable(feature = "cow_box_error", since = "1.22.0")]
387 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
388 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
393 /// use std::error::Error;
395 /// use std::borrow::Cow;
397 /// let a_cow_str_error = Cow::from("a str error");
398 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
400 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
402 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
403 From::from(String::from(err))
407 #[stable(feature = "cow_box_error", since = "1.22.0")]
408 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
409 /// Converts a [`Cow`] into a box of dyn [`Error`].
414 /// use std::error::Error;
416 /// use std::borrow::Cow;
418 /// let a_cow_str_error = Cow::from("a str error");
419 /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
420 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
422 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
423 From::from(String::from(err))
427 #[unstable(feature = "never_type", issue = "35121")]
429 fn description(&self) -> &str { *self }
432 #[unstable(feature = "allocator_api",
433 reason = "the precise API and guarantees it provides may be tweaked.",
435 impl Error for AllocErr {
436 fn description(&self) -> &str {
437 "memory allocation failed"
441 #[unstable(feature = "allocator_api",
442 reason = "the precise API and guarantees it provides may be tweaked.",
444 impl Error for LayoutErr {
445 fn description(&self) -> &str {
446 "invalid parameters to Layout::from_size_align"
450 #[unstable(feature = "allocator_api",
451 reason = "the precise API and guarantees it provides may be tweaked.",
453 impl Error for CannotReallocInPlace {
454 fn description(&self) -> &str {
455 CannotReallocInPlace::description(self)
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl Error for str::ParseBoolError {
461 fn description(&self) -> &str { "failed to parse bool" }
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl Error for str::Utf8Error {
466 fn description(&self) -> &str {
467 "invalid utf-8: corrupt contents"
471 #[stable(feature = "rust1", since = "1.0.0")]
472 impl Error for num::ParseIntError {
473 fn description(&self) -> &str {
478 #[stable(feature = "try_from", since = "1.34.0")]
479 impl Error for num::TryFromIntError {
480 fn description(&self) -> &str {
485 #[stable(feature = "try_from", since = "1.34.0")]
486 impl Error for array::TryFromSliceError {
487 fn description(&self) -> &str {
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl Error for num::ParseFloatError {
494 fn description(&self) -> &str {
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl Error for string::FromUtf8Error {
501 fn description(&self) -> &str {
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl Error for string::FromUtf16Error {
508 fn description(&self) -> &str {
513 #[stable(feature = "str_parse_error2", since = "1.8.0")]
514 impl Error for string::ParseError {
515 fn description(&self) -> &str {
520 #[stable(feature = "decode_utf16", since = "1.9.0")]
521 impl Error for char::DecodeUtf16Error {
522 fn description(&self) -> &str {
523 "unpaired surrogate found"
527 #[stable(feature = "box_error", since = "1.8.0")]
528 impl<T: Error> Error for Box<T> {
529 fn description(&self) -> &str {
530 Error::description(&**self)
534 fn cause(&self) -> Option<&dyn Error> {
535 Error::cause(&**self)
539 #[stable(feature = "fmt_error", since = "1.11.0")]
540 impl Error for fmt::Error {
541 fn description(&self) -> &str {
542 "an error occurred when formatting an argument"
546 #[stable(feature = "try_borrow", since = "1.13.0")]
547 impl Error for cell::BorrowError {
548 fn description(&self) -> &str {
549 "already mutably borrowed"
553 #[stable(feature = "try_borrow", since = "1.13.0")]
554 impl Error for cell::BorrowMutError {
555 fn description(&self) -> &str {
560 #[stable(feature = "try_from", since = "1.34.0")]
561 impl Error for char::CharTryFromError {
562 fn description(&self) -> &str {
563 "converted integer out of range for `char`"
567 #[stable(feature = "char_from_str", since = "1.20.0")]
568 impl Error for char::ParseCharError {
569 fn description(&self) -> &str {
574 // copied from any.rs
575 impl dyn Error + 'static {
576 /// Returns `true` if the boxed type is the same as `T`
577 #[stable(feature = "error_downcast", since = "1.3.0")]
579 pub fn is<T: Error + 'static>(&self) -> bool {
580 // Get TypeId of the type this function is instantiated with
581 let t = TypeId::of::<T>();
583 // Get TypeId of the type in the trait object
584 let boxed = self.type_id();
586 // Compare both TypeIds on equality
590 /// Returns some reference to the boxed value if it is of type `T`, or
591 /// `None` if it isn't.
592 #[stable(feature = "error_downcast", since = "1.3.0")]
594 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
597 Some(&*(self as *const dyn Error as *const T))
604 /// Returns some mutable reference to the boxed value if it is of type `T`, or
605 /// `None` if it isn't.
606 #[stable(feature = "error_downcast", since = "1.3.0")]
608 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
611 Some(&mut *(self as *mut dyn Error as *mut T))
619 impl dyn Error + 'static + Send {
620 /// Forwards to the method defined on the type `Any`.
621 #[stable(feature = "error_downcast", since = "1.3.0")]
623 pub fn is<T: Error + 'static>(&self) -> bool {
624 <dyn Error + 'static>::is::<T>(self)
627 /// Forwards to the method defined on the type `Any`.
628 #[stable(feature = "error_downcast", since = "1.3.0")]
630 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
631 <dyn Error + 'static>::downcast_ref::<T>(self)
634 /// Forwards to the method defined on the type `Any`.
635 #[stable(feature = "error_downcast", since = "1.3.0")]
637 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
638 <dyn Error + 'static>::downcast_mut::<T>(self)
642 impl dyn Error + 'static + Send + Sync {
643 /// Forwards to the method defined on the type `Any`.
644 #[stable(feature = "error_downcast", since = "1.3.0")]
646 pub fn is<T: Error + 'static>(&self) -> bool {
647 <dyn Error + 'static>::is::<T>(self)
650 /// Forwards to the method defined on the type `Any`.
651 #[stable(feature = "error_downcast", since = "1.3.0")]
653 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
654 <dyn Error + 'static>::downcast_ref::<T>(self)
657 /// Forwards to the method defined on the type `Any`.
658 #[stable(feature = "error_downcast", since = "1.3.0")]
660 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
661 <dyn Error + 'static>::downcast_mut::<T>(self)
667 #[stable(feature = "error_downcast", since = "1.3.0")]
668 /// Attempt to downcast the box to a concrete type.
669 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
672 let raw: *mut dyn Error = Box::into_raw(self);
673 Ok(Box::from_raw(raw as *mut T))
680 /// Returns an iterator starting with the current error and continuing with
681 /// recursively calling [`source`].
686 /// #![feature(error_iter)]
687 /// use std::error::Error;
694 /// struct B(Option<Box<dyn Error + 'static>>);
696 /// impl fmt::Display for A {
697 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 /// impl fmt::Display for B {
703 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
708 /// impl Error for A {}
710 /// impl Error for B {
711 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
712 /// self.0.as_ref().map(|e| e.as_ref())
716 /// let b = B(Some(Box::new(A)));
718 /// // let err : Box<Error> = b.into(); // or
719 /// let err = &b as &(dyn Error);
721 /// let mut iter = err.iter_chain();
723 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
724 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
725 /// assert!(iter.next().is_none());
726 /// assert!(iter.next().is_none());
729 /// [`source`]: trait.Error.html#method.source
730 #[unstable(feature = "error_iter", issue = "58520")]
732 pub fn iter_chain(&self) -> ErrorIter<'_> {
738 /// Returns an iterator starting with the [`source`] of this error
739 /// and continuing with recursively calling [`source`].
744 /// #![feature(error_iter)]
745 /// use std::error::Error;
752 /// struct B(Option<Box<dyn Error + 'static>>);
755 /// struct C(Option<Box<dyn Error + 'static>>);
757 /// impl fmt::Display for A {
758 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 /// impl fmt::Display for B {
764 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 /// impl fmt::Display for C {
770 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775 /// impl Error for A {}
777 /// impl Error for B {
778 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
779 /// self.0.as_ref().map(|e| e.as_ref())
783 /// impl Error for C {
784 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
785 /// self.0.as_ref().map(|e| e.as_ref())
789 /// let b = B(Some(Box::new(A)));
790 /// let c = C(Some(Box::new(b)));
792 /// // let err : Box<Error> = c.into(); // or
793 /// let err = &c as &(dyn Error);
795 /// let mut iter = err.iter_sources();
797 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
798 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
799 /// assert!(iter.next().is_none());
800 /// assert!(iter.next().is_none());
803 /// [`source`]: trait.Error.html#method.source
805 #[unstable(feature = "error_iter", issue = "58520")]
806 pub fn iter_sources(&self) -> ErrorIter<'_> {
808 current: self.source(),
813 /// An iterator over [`Error`]
815 /// [`Error`]: trait.Error.html
816 #[unstable(feature = "error_iter", issue = "58520")]
817 #[derive(Copy, Clone, Debug)]
818 pub struct ErrorIter<'a> {
819 current: Option<&'a (dyn Error + 'static)>,
822 #[unstable(feature = "error_iter", issue = "58520")]
823 impl<'a> Iterator for ErrorIter<'a> {
824 type Item = &'a (dyn Error + 'static);
826 fn next(&mut self) -> Option<Self::Item> {
827 let current = self.current;
828 self.current = self.current.and_then(Error::source);
833 impl dyn Error + Send {
835 #[stable(feature = "error_downcast", since = "1.3.0")]
836 /// Attempt to downcast the box to a concrete type.
837 pub fn downcast<T: Error + 'static>(self: Box<Self>)
838 -> Result<Box<T>, Box<dyn Error + Send>> {
839 let err: Box<dyn Error> = self;
840 <dyn Error>::downcast(err).map_err(|s| unsafe {
841 // reapply the Send marker
842 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
847 impl dyn Error + Send + Sync {
849 #[stable(feature = "error_downcast", since = "1.3.0")]
850 /// Attempt to downcast the box to a concrete type.
851 pub fn downcast<T: Error + 'static>(self: Box<Self>)
852 -> Result<Box<T>, Box<Self>> {
853 let err: Box<dyn Error> = self;
854 <dyn Error>::downcast(err).map_err(|s| unsafe {
855 // reapply the Send+Sync marker
856 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
866 #[derive(Debug, PartialEq)]
868 #[derive(Debug, PartialEq)]
871 impl fmt::Display for A {
872 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
876 impl fmt::Display for B {
877 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 fn description(&self) -> &str { "A-desc" }
886 fn description(&self) -> &str { "A-desc" }
892 let a = &mut a as &mut (dyn Error + 'static);
893 assert_eq!(a.downcast_ref::<A>(), Some(&A));
894 assert_eq!(a.downcast_ref::<B>(), None);
895 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
896 assert_eq!(a.downcast_mut::<B>(), None);
898 let a: Box<dyn Error> = Box::new(A);
899 match a.downcast::<B>() {
900 Ok(..) => panic!("expected error"),
901 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),