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.
16 use alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
22 use fmt::{self, Debug, Display};
28 /// `Error` is a trait representing the basic expectations for error values,
29 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
30 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
31 /// cause chain information:
33 /// The [`source`] method is generally used when errors cross "abstraction
34 /// boundaries". If one module must report an error that is caused by an error
35 /// from a lower-level module, it can allow access to that error via the
36 /// [`source`] method. This makes it possible for the high-level module to
37 /// provide its own errors while also revealing some of the implementation for
38 /// debugging via [`source`] chains.
40 /// [`Result<T, E>`]: ../result/enum.Result.html
41 /// [`Display`]: ../fmt/trait.Display.html
42 /// [`Debug`]: ../fmt/trait.Debug.html
43 /// [`source`]: trait.Error.html#method.source
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub trait Error: Debug + Display {
46 /// **This method is soft-deprecated.**
48 /// Although using it won’t cause compilation warning,
49 /// new code should use [`Display`] instead
50 /// and new `impl`s can omit it.
52 /// To obtain error description as a string, use `to_string()`.
54 /// [`Display`]: ../fmt/trait.Display.html
59 /// match "xc".parse::<u32>() {
61 /// // Print `e` itself, not `e.description()`.
62 /// println!("Error: {}", e);
64 /// _ => println!("No error"),
67 #[stable(feature = "rust1", since = "1.0.0")]
68 fn description(&self) -> &str {
69 "description() is deprecated; use Display"
72 /// The lower-level cause of this error, if any.
77 /// use std::error::Error;
81 /// struct SuperError {
82 /// side: SuperErrorSideKick,
85 /// impl fmt::Display for SuperError {
86 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87 /// write!(f, "SuperError is here!")
91 /// impl Error for SuperError {
92 /// fn description(&self) -> &str {
93 /// "I'm the superhero of errors"
96 /// fn cause(&self) -> Option<&Error> {
102 /// struct SuperErrorSideKick;
104 /// impl fmt::Display for SuperErrorSideKick {
105 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 /// write!(f, "SuperErrorSideKick is here!")
110 /// impl Error for SuperErrorSideKick {
111 /// fn description(&self) -> &str {
112 /// "I'm SuperError side kick"
116 /// fn get_super_error() -> Result<(), SuperError> {
117 /// Err(SuperError { side: SuperErrorSideKick })
121 /// match get_super_error() {
123 /// println!("Error: {}", e.description());
124 /// println!("Caused by: {}", e.cause().unwrap());
126 /// _ => println!("No error"),
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
133 fn cause(&self) -> Option<&dyn Error> {
137 /// The lower-level source of this error, if any.
142 /// use std::error::Error;
146 /// struct SuperError {
147 /// side: SuperErrorSideKick,
150 /// impl fmt::Display for SuperError {
151 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 /// write!(f, "SuperError is here!")
156 /// impl Error for SuperError {
157 /// fn description(&self) -> &str {
158 /// "I'm the superhero of errors"
161 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
167 /// struct SuperErrorSideKick;
169 /// impl fmt::Display for SuperErrorSideKick {
170 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 /// write!(f, "SuperErrorSideKick is here!")
175 /// impl Error for SuperErrorSideKick {
176 /// fn description(&self) -> &str {
177 /// "I'm SuperError side kick"
181 /// fn get_super_error() -> Result<(), SuperError> {
182 /// Err(SuperError { side: SuperErrorSideKick })
186 /// match get_super_error() {
188 /// println!("Error: {}", e.description());
189 /// println!("Caused by: {}", e.source().unwrap());
191 /// _ => println!("No error"),
195 #[stable(feature = "error_source", since = "1.30.0")]
196 fn source(&self) -> Option<&(dyn Error + 'static)> { None }
198 /// Gets the `TypeId` of `self`
200 #[stable(feature = "error_type_id", since = "1.34.0")]
201 fn type_id(&self) -> TypeId where Self: 'static {
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
208 /// Converts a type of [`Error`] into a box of dyn [`Error`].
213 /// use std::error::Error;
220 /// impl fmt::Display for AnError {
221 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
222 /// write!(f , "An error")
226 /// impl Error for AnError {
227 /// fn description(&self) -> &str {
228 /// "Description of an error"
232 /// let an_error = AnError;
233 /// assert!(0 == mem::size_of_val(&an_error));
234 /// let a_boxed_error = Box::<Error>::from(an_error);
235 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
237 fn from(err: E) -> Box<dyn Error + 'a> {
242 #[stable(feature = "rust1", since = "1.0.0")]
243 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
244 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
245 /// [`Send`] + [`Sync`].
250 /// use std::error::Error;
257 /// impl fmt::Display for AnError {
258 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
259 /// write!(f , "An error")
263 /// impl Error for AnError {
264 /// fn description(&self) -> &str {
265 /// "Description of an error"
269 /// unsafe impl Send for AnError {}
271 /// unsafe impl Sync for AnError {}
273 /// let an_error = AnError;
274 /// assert!(0 == mem::size_of_val(&an_error));
275 /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
277 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
279 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl From<String> for Box<dyn Error + Send + Sync> {
286 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
291 /// use std::error::Error;
294 /// let a_string_error = "a string error".to_string();
295 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
297 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
299 fn from(err: String) -> Box<dyn Error + Send + Sync> {
301 struct StringError(String);
303 impl Error for StringError {
304 fn description(&self) -> &str { &self.0 }
307 impl Display for StringError {
308 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
309 Display::fmt(&self.0, f)
313 Box::new(StringError(err))
317 #[stable(feature = "string_box_error", since = "1.6.0")]
318 impl From<String> for Box<dyn Error> {
319 /// Converts a [`String`] into a box of dyn [`Error`].
324 /// use std::error::Error;
327 /// let a_string_error = "a string error".to_string();
328 /// let a_boxed_error = Box::<Error>::from(a_string_error);
329 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
331 fn from(str_err: String) -> Box<dyn Error> {
332 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
333 let err2: Box<dyn Error> = err1;
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<'a, 'b> From<&'b str> for Box<dyn Error + Send + Sync + 'a> {
340 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
345 /// use std::error::Error;
348 /// let a_str_error = "a str error";
349 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
351 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
353 fn from(err: &'b str) -> Box<dyn Error + Send + Sync + 'a> {
354 From::from(String::from(err))
358 #[stable(feature = "string_box_error", since = "1.6.0")]
359 impl<'a> From<&'a str> for Box<dyn Error> {
360 /// Converts a [`str`] into a box of dyn [`Error`].
365 /// use std::error::Error;
368 /// let a_str_error = "a str error";
369 /// let a_boxed_error = Box::<Error>::from(a_str_error);
370 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
372 fn from(err: &'a str) -> Box<dyn Error> {
373 From::from(String::from(err))
377 #[stable(feature = "cow_box_error", since = "1.22.0")]
378 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
379 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
384 /// use std::error::Error;
386 /// use std::borrow::Cow;
388 /// let a_cow_str_error = Cow::from("a str error");
389 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
391 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
393 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
394 From::from(String::from(err))
398 #[stable(feature = "cow_box_error", since = "1.22.0")]
399 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
400 /// Converts a [`Cow`] into a box of dyn [`Error`].
405 /// use std::error::Error;
407 /// use std::borrow::Cow;
409 /// let a_cow_str_error = Cow::from("a str error");
410 /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
411 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
413 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
414 From::from(String::from(err))
418 #[unstable(feature = "never_type", issue = "35121")]
420 fn description(&self) -> &str { *self }
423 #[unstable(feature = "allocator_api",
424 reason = "the precise API and guarantees it provides may be tweaked.",
426 impl Error for AllocErr {
427 fn description(&self) -> &str {
428 "memory allocation failed"
432 #[unstable(feature = "allocator_api",
433 reason = "the precise API and guarantees it provides may be tweaked.",
435 impl Error for LayoutErr {
436 fn description(&self) -> &str {
437 "invalid parameters to Layout::from_size_align"
441 #[unstable(feature = "allocator_api",
442 reason = "the precise API and guarantees it provides may be tweaked.",
444 impl Error for CannotReallocInPlace {
445 fn description(&self) -> &str {
446 CannotReallocInPlace::description(self)
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl Error for str::ParseBoolError {
452 fn description(&self) -> &str { "failed to parse bool" }
455 #[stable(feature = "rust1", since = "1.0.0")]
456 impl Error for str::Utf8Error {
457 fn description(&self) -> &str {
458 "invalid utf-8: corrupt contents"
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl Error for num::ParseIntError {
464 fn description(&self) -> &str {
469 #[unstable(feature = "try_from", issue = "33417")]
470 impl Error for num::TryFromIntError {
471 fn description(&self) -> &str {
476 #[unstable(feature = "try_from", issue = "33417")]
477 impl Error for array::TryFromSliceError {
478 fn description(&self) -> &str {
483 #[stable(feature = "rust1", since = "1.0.0")]
484 impl Error for num::ParseFloatError {
485 fn description(&self) -> &str {
490 #[stable(feature = "rust1", since = "1.0.0")]
491 impl Error for string::FromUtf8Error {
492 fn description(&self) -> &str {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl Error for string::FromUtf16Error {
499 fn description(&self) -> &str {
504 #[stable(feature = "str_parse_error2", since = "1.8.0")]
505 impl Error for string::ParseError {
506 fn description(&self) -> &str {
511 #[stable(feature = "decode_utf16", since = "1.9.0")]
512 impl Error for char::DecodeUtf16Error {
513 fn description(&self) -> &str {
514 "unpaired surrogate found"
518 #[stable(feature = "box_error", since = "1.8.0")]
519 impl<T: Error> Error for Box<T> {
520 fn description(&self) -> &str {
521 Error::description(&**self)
525 fn cause(&self) -> Option<&dyn Error> {
526 Error::cause(&**self)
530 #[stable(feature = "fmt_error", since = "1.11.0")]
531 impl Error for fmt::Error {
532 fn description(&self) -> &str {
533 "an error occurred when formatting an argument"
537 #[stable(feature = "try_borrow", since = "1.13.0")]
538 impl Error for cell::BorrowError {
539 fn description(&self) -> &str {
540 "already mutably borrowed"
544 #[stable(feature = "try_borrow", since = "1.13.0")]
545 impl Error for cell::BorrowMutError {
546 fn description(&self) -> &str {
551 #[unstable(feature = "try_from", issue = "33417")]
552 impl Error for char::CharTryFromError {
553 fn description(&self) -> &str {
554 "converted integer out of range for `char`"
558 #[stable(feature = "char_from_str", since = "1.20.0")]
559 impl Error for char::ParseCharError {
560 fn description(&self) -> &str {
565 // copied from any.rs
566 impl dyn Error + 'static {
567 /// Returns `true` if the boxed type is the same as `T`
568 #[stable(feature = "error_downcast", since = "1.3.0")]
570 pub fn is<T: Error + 'static>(&self) -> bool {
571 // Get TypeId of the type this function is instantiated with
572 let t = TypeId::of::<T>();
574 // Get TypeId of the type in the trait object
575 let boxed = self.type_id();
577 // Compare both TypeIds on equality
581 /// Returns some reference to the boxed value if it is of type `T`, or
582 /// `None` if it isn't.
583 #[stable(feature = "error_downcast", since = "1.3.0")]
585 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
588 Some(&*(self as *const dyn Error as *const T))
595 /// Returns some mutable reference to the boxed value if it is of type `T`, or
596 /// `None` if it isn't.
597 #[stable(feature = "error_downcast", since = "1.3.0")]
599 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
602 Some(&mut *(self as *mut dyn Error as *mut T))
610 impl dyn Error + 'static + Send {
611 /// Forwards to the method defined on the type `Any`.
612 #[stable(feature = "error_downcast", since = "1.3.0")]
614 pub fn is<T: Error + 'static>(&self) -> bool {
615 <dyn Error + 'static>::is::<T>(self)
618 /// Forwards to the method defined on the type `Any`.
619 #[stable(feature = "error_downcast", since = "1.3.0")]
621 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
622 <dyn Error + 'static>::downcast_ref::<T>(self)
625 /// Forwards to the method defined on the type `Any`.
626 #[stable(feature = "error_downcast", since = "1.3.0")]
628 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
629 <dyn Error + 'static>::downcast_mut::<T>(self)
633 impl dyn Error + 'static + Send + Sync {
634 /// Forwards to the method defined on the type `Any`.
635 #[stable(feature = "error_downcast", since = "1.3.0")]
637 pub fn is<T: Error + 'static>(&self) -> bool {
638 <dyn Error + 'static>::is::<T>(self)
641 /// Forwards to the method defined on the type `Any`.
642 #[stable(feature = "error_downcast", since = "1.3.0")]
644 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
645 <dyn Error + 'static>::downcast_ref::<T>(self)
648 /// Forwards to the method defined on the type `Any`.
649 #[stable(feature = "error_downcast", since = "1.3.0")]
651 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
652 <dyn Error + 'static>::downcast_mut::<T>(self)
658 #[stable(feature = "error_downcast", since = "1.3.0")]
659 /// Attempt to downcast the box to a concrete type.
660 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
663 let raw: *mut dyn Error = Box::into_raw(self);
664 Ok(Box::from_raw(raw as *mut T))
671 /// Returns an iterator starting with the current error and continuing with
672 /// recursively calling [`source`].
677 /// #![feature(error_iter)]
678 /// use std::error::Error;
685 /// struct B(Option<Box<dyn Error + 'static>>);
687 /// impl fmt::Display for A {
688 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
693 /// impl fmt::Display for B {
694 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
699 /// impl Error for A {}
701 /// impl Error for B {
702 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
703 /// self.0.as_ref().map(|e| e.as_ref())
707 /// let b = B(Some(Box::new(A)));
709 /// // let err : Box<Error> = b.into(); // or
710 /// let err = &b as &(dyn Error);
712 /// let mut iter = err.iter_chain();
714 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
715 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
716 /// assert!(iter.next().is_none());
717 /// assert!(iter.next().is_none());
720 /// [`source`]: trait.Error.html#method.source
721 #[unstable(feature = "error_iter", issue = "58289")]
723 pub fn iter_chain(&self) -> ErrorIter {
729 /// Returns an iterator starting with the [`source`] of this error
730 /// and continuing with recursively calling [`source`].
735 /// #![feature(error_iter)]
736 /// use std::error::Error;
743 /// struct B(Option<Box<dyn Error + 'static>>);
746 /// struct C(Option<Box<dyn Error + 'static>>);
748 /// impl fmt::Display for A {
749 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
754 /// impl fmt::Display for B {
755 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
760 /// impl fmt::Display for C {
761 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
766 /// impl Error for A {}
768 /// impl Error for B {
769 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
770 /// self.0.as_ref().map(|e| e.as_ref())
774 /// impl Error for C {
775 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
776 /// self.0.as_ref().map(|e| e.as_ref())
780 /// let b = B(Some(Box::new(A)));
781 /// let c = C(Some(Box::new(b)));
783 /// // let err : Box<Error> = c.into(); // or
784 /// let err = &c as &(dyn Error);
786 /// let mut iter = err.iter_sources();
788 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
789 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
790 /// assert!(iter.next().is_none());
791 /// assert!(iter.next().is_none());
794 /// [`source`]: trait.Error.html#method.source
796 #[unstable(feature = "error_iter", issue = "58289")]
797 pub fn iter_sources(&self) -> ErrorIter {
799 current: self.source(),
804 /// An iterator over [`Error`]
806 /// [`Error`]: trait.Error.html
807 #[unstable(feature = "error_iter", issue = "58289")]
808 #[derive(Copy, Clone, Debug)]
809 pub struct ErrorIter<'a> {
810 current: Option<&'a (dyn Error + 'static)>,
813 #[unstable(feature = "error_iter", issue = "58289")]
814 impl<'a> Iterator for ErrorIter<'a> {
815 type Item = &'a (dyn Error + 'static);
817 fn next(&mut self) -> Option<Self::Item> {
818 let current = self.current;
819 self.current = self.current.and_then(Error::source);
824 impl dyn Error + Send {
826 #[stable(feature = "error_downcast", since = "1.3.0")]
827 /// Attempt to downcast the box to a concrete type.
828 pub fn downcast<T: Error + 'static>(self: Box<Self>)
829 -> Result<Box<T>, Box<dyn Error + Send>> {
830 let err: Box<dyn Error> = self;
831 <dyn Error>::downcast(err).map_err(|s| unsafe {
832 // reapply the Send marker
833 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
838 impl dyn Error + Send + Sync {
840 #[stable(feature = "error_downcast", since = "1.3.0")]
841 /// Attempt to downcast the box to a concrete type.
842 pub fn downcast<T: Error + 'static>(self: Box<Self>)
843 -> Result<Box<T>, Box<Self>> {
844 let err: Box<dyn Error> = self;
845 <dyn Error>::downcast(err).map_err(|s| unsafe {
846 // reapply the Send+Sync marker
847 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
857 #[derive(Debug, PartialEq)]
859 #[derive(Debug, PartialEq)]
862 impl fmt::Display for A {
863 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
867 impl fmt::Display for B {
868 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
874 fn description(&self) -> &str { "A-desc" }
877 fn description(&self) -> &str { "A-desc" }
883 let a = &mut a as &mut (dyn Error + 'static);
884 assert_eq!(a.downcast_ref::<A>(), Some(&A));
885 assert_eq!(a.downcast_ref::<B>(), None);
886 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
887 assert_eq!(a.downcast_mut::<B>(), None);
889 let a: Box<dyn Error> = Box::new(A);
890 match a.downcast::<B>() {
891 Ok(..) => panic!("expected error"),
892 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),