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> {
304 struct StringError(String);
306 impl Error for StringError {
307 fn description(&self) -> &str { &self.0 }
310 impl Display for StringError {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 Display::fmt(&self.0, f)
316 Box::new(StringError(err))
320 #[stable(feature = "string_box_error", since = "1.6.0")]
321 impl From<String> for Box<dyn Error> {
322 /// Converts a [`String`] into a box of dyn [`Error`].
327 /// use std::error::Error;
330 /// let a_string_error = "a string error".to_string();
331 /// let a_boxed_error = Box::<Error>::from(a_string_error);
332 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
334 fn from(str_err: String) -> Box<dyn Error> {
335 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
336 let err2: Box<dyn Error> = err1;
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
343 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
348 /// use std::error::Error;
351 /// let a_str_error = "a str error";
352 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
354 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
356 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
357 From::from(String::from(err))
361 #[stable(feature = "string_box_error", since = "1.6.0")]
362 impl From<&str> for Box<dyn Error> {
363 /// Converts a [`str`] into a box of dyn [`Error`].
368 /// use std::error::Error;
371 /// let a_str_error = "a str error";
372 /// let a_boxed_error = Box::<Error>::from(a_str_error);
373 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
375 fn from(err: &str) -> Box<dyn Error> {
376 From::from(String::from(err))
380 #[stable(feature = "cow_box_error", since = "1.22.0")]
381 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
382 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
387 /// use std::error::Error;
389 /// use std::borrow::Cow;
391 /// let a_cow_str_error = Cow::from("a str error");
392 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
394 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
396 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
397 From::from(String::from(err))
401 #[stable(feature = "cow_box_error", since = "1.22.0")]
402 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
403 /// Converts a [`Cow`] into a box of dyn [`Error`].
408 /// use std::error::Error;
410 /// use std::borrow::Cow;
412 /// let a_cow_str_error = Cow::from("a str error");
413 /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
414 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
416 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
417 From::from(String::from(err))
421 #[unstable(feature = "never_type", issue = "35121")]
423 fn description(&self) -> &str { *self }
426 #[unstable(feature = "allocator_api",
427 reason = "the precise API and guarantees it provides may be tweaked.",
429 impl Error for AllocErr {
430 fn description(&self) -> &str {
431 "memory allocation failed"
435 #[unstable(feature = "allocator_api",
436 reason = "the precise API and guarantees it provides may be tweaked.",
438 impl Error for LayoutErr {
439 fn description(&self) -> &str {
440 "invalid parameters to Layout::from_size_align"
444 #[unstable(feature = "allocator_api",
445 reason = "the precise API and guarantees it provides may be tweaked.",
447 impl Error for CannotReallocInPlace {
448 fn description(&self) -> &str {
449 CannotReallocInPlace::description(self)
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl Error for str::ParseBoolError {
455 fn description(&self) -> &str { "failed to parse bool" }
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl Error for str::Utf8Error {
460 fn description(&self) -> &str {
461 "invalid utf-8: corrupt contents"
465 #[stable(feature = "rust1", since = "1.0.0")]
466 impl Error for num::ParseIntError {
467 fn description(&self) -> &str {
472 #[stable(feature = "try_from", since = "1.34.0")]
473 impl Error for num::TryFromIntError {
474 fn description(&self) -> &str {
479 #[stable(feature = "try_from", since = "1.34.0")]
480 impl Error for array::TryFromSliceError {
481 fn description(&self) -> &str {
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl Error for num::ParseFloatError {
488 fn description(&self) -> &str {
493 #[stable(feature = "rust1", since = "1.0.0")]
494 impl Error for string::FromUtf8Error {
495 fn description(&self) -> &str {
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl Error for string::FromUtf16Error {
502 fn description(&self) -> &str {
507 #[stable(feature = "str_parse_error2", since = "1.8.0")]
508 impl Error for string::ParseError {
509 fn description(&self) -> &str {
514 #[stable(feature = "decode_utf16", since = "1.9.0")]
515 impl Error for char::DecodeUtf16Error {
516 fn description(&self) -> &str {
517 "unpaired surrogate found"
521 #[stable(feature = "box_error", since = "1.8.0")]
522 impl<T: Error> Error for Box<T> {
523 fn description(&self) -> &str {
524 Error::description(&**self)
528 fn cause(&self) -> Option<&dyn Error> {
529 Error::cause(&**self)
533 #[stable(feature = "fmt_error", since = "1.11.0")]
534 impl Error for fmt::Error {
535 fn description(&self) -> &str {
536 "an error occurred when formatting an argument"
540 #[stable(feature = "try_borrow", since = "1.13.0")]
541 impl Error for cell::BorrowError {
542 fn description(&self) -> &str {
543 "already mutably borrowed"
547 #[stable(feature = "try_borrow", since = "1.13.0")]
548 impl Error for cell::BorrowMutError {
549 fn description(&self) -> &str {
554 #[stable(feature = "try_from", since = "1.34.0")]
555 impl Error for char::CharTryFromError {
556 fn description(&self) -> &str {
557 "converted integer out of range for `char`"
561 #[stable(feature = "char_from_str", since = "1.20.0")]
562 impl Error for char::ParseCharError {
563 fn description(&self) -> &str {
568 // copied from any.rs
569 impl dyn Error + 'static {
570 /// Returns `true` if the boxed type is the same as `T`
571 #[stable(feature = "error_downcast", since = "1.3.0")]
573 pub fn is<T: Error + 'static>(&self) -> bool {
574 // Get TypeId of the type this function is instantiated with
575 let t = TypeId::of::<T>();
577 // Get TypeId of the type in the trait object
578 let boxed = self.type_id();
580 // Compare both TypeIds on equality
584 /// Returns some reference to the boxed value if it is of type `T`, or
585 /// `None` if it isn't.
586 #[stable(feature = "error_downcast", since = "1.3.0")]
588 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
591 Some(&*(self as *const dyn Error as *const T))
598 /// Returns some mutable reference to the boxed value if it is of type `T`, or
599 /// `None` if it isn't.
600 #[stable(feature = "error_downcast", since = "1.3.0")]
602 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
605 Some(&mut *(self as *mut dyn Error as *mut T))
613 impl dyn Error + 'static + Send {
614 /// Forwards to the method defined on the type `Any`.
615 #[stable(feature = "error_downcast", since = "1.3.0")]
617 pub fn is<T: Error + 'static>(&self) -> bool {
618 <dyn Error + 'static>::is::<T>(self)
621 /// Forwards to the method defined on the type `Any`.
622 #[stable(feature = "error_downcast", since = "1.3.0")]
624 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
625 <dyn Error + 'static>::downcast_ref::<T>(self)
628 /// Forwards to the method defined on the type `Any`.
629 #[stable(feature = "error_downcast", since = "1.3.0")]
631 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
632 <dyn Error + 'static>::downcast_mut::<T>(self)
636 impl dyn Error + 'static + Send + Sync {
637 /// Forwards to the method defined on the type `Any`.
638 #[stable(feature = "error_downcast", since = "1.3.0")]
640 pub fn is<T: Error + 'static>(&self) -> bool {
641 <dyn Error + 'static>::is::<T>(self)
644 /// Forwards to the method defined on the type `Any`.
645 #[stable(feature = "error_downcast", since = "1.3.0")]
647 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
648 <dyn Error + 'static>::downcast_ref::<T>(self)
651 /// Forwards to the method defined on the type `Any`.
652 #[stable(feature = "error_downcast", since = "1.3.0")]
654 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
655 <dyn Error + 'static>::downcast_mut::<T>(self)
661 #[stable(feature = "error_downcast", since = "1.3.0")]
662 /// Attempt to downcast the box to a concrete type.
663 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
666 let raw: *mut dyn Error = Box::into_raw(self);
667 Ok(Box::from_raw(raw as *mut T))
674 /// Returns an iterator starting with the current error and continuing with
675 /// recursively calling [`source`].
680 /// #![feature(error_iter)]
681 /// use std::error::Error;
688 /// struct B(Option<Box<dyn Error + 'static>>);
690 /// impl fmt::Display for A {
691 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696 /// impl fmt::Display for B {
697 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
702 /// impl Error for A {}
704 /// impl Error for B {
705 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
706 /// self.0.as_ref().map(|e| e.as_ref())
710 /// let b = B(Some(Box::new(A)));
712 /// // let err : Box<Error> = b.into(); // or
713 /// let err = &b as &(dyn Error);
715 /// let mut iter = err.iter_chain();
717 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
718 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
719 /// assert!(iter.next().is_none());
720 /// assert!(iter.next().is_none());
723 /// [`source`]: trait.Error.html#method.source
724 #[unstable(feature = "error_iter", issue = "58520")]
726 pub fn iter_chain(&self) -> ErrorIter<'_> {
732 /// Returns an iterator starting with the [`source`] of this error
733 /// and continuing with recursively calling [`source`].
738 /// #![feature(error_iter)]
739 /// use std::error::Error;
746 /// struct B(Option<Box<dyn Error + 'static>>);
749 /// struct C(Option<Box<dyn Error + 'static>>);
751 /// impl fmt::Display for A {
752 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 /// impl fmt::Display for B {
758 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763 /// impl fmt::Display for C {
764 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 /// impl Error for A {}
771 /// impl Error for B {
772 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
773 /// self.0.as_ref().map(|e| e.as_ref())
777 /// impl Error for C {
778 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
779 /// self.0.as_ref().map(|e| e.as_ref())
783 /// let b = B(Some(Box::new(A)));
784 /// let c = C(Some(Box::new(b)));
786 /// // let err : Box<Error> = c.into(); // or
787 /// let err = &c as &(dyn Error);
789 /// let mut iter = err.iter_sources();
791 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
792 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
793 /// assert!(iter.next().is_none());
794 /// assert!(iter.next().is_none());
797 /// [`source`]: trait.Error.html#method.source
799 #[unstable(feature = "error_iter", issue = "58520")]
800 pub fn iter_sources(&self) -> ErrorIter<'_> {
802 current: self.source(),
807 /// An iterator over [`Error`]
809 /// [`Error`]: trait.Error.html
810 #[unstable(feature = "error_iter", issue = "58520")]
811 #[derive(Copy, Clone, Debug)]
812 pub struct ErrorIter<'a> {
813 current: Option<&'a (dyn Error + 'static)>,
816 #[unstable(feature = "error_iter", issue = "58520")]
817 impl<'a> Iterator for ErrorIter<'a> {
818 type Item = &'a (dyn Error + 'static);
820 fn next(&mut self) -> Option<Self::Item> {
821 let current = self.current;
822 self.current = self.current.and_then(Error::source);
827 impl dyn Error + Send {
829 #[stable(feature = "error_downcast", since = "1.3.0")]
830 /// Attempt to downcast the box to a concrete type.
831 pub fn downcast<T: Error + 'static>(self: Box<Self>)
832 -> Result<Box<T>, Box<dyn Error + Send>> {
833 let err: Box<dyn Error> = self;
834 <dyn Error>::downcast(err).map_err(|s| unsafe {
835 // reapply the Send marker
836 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
841 impl dyn Error + Send + Sync {
843 #[stable(feature = "error_downcast", since = "1.3.0")]
844 /// Attempt to downcast the box to a concrete type.
845 pub fn downcast<T: Error + 'static>(self: Box<Self>)
846 -> Result<Box<T>, Box<Self>> {
847 let err: Box<dyn Error> = self;
848 <dyn Error>::downcast(err).map_err(|s| unsafe {
849 // reapply the Send+Sync marker
850 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
860 #[derive(Debug, PartialEq)]
862 #[derive(Debug, PartialEq)]
865 impl fmt::Display for A {
866 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870 impl fmt::Display for B {
871 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
877 fn description(&self) -> &str { "A-desc" }
880 fn description(&self) -> &str { "A-desc" }
886 let a = &mut a as &mut (dyn Error + 'static);
887 assert_eq!(a.downcast_ref::<A>(), Some(&A));
888 assert_eq!(a.downcast_ref::<B>(), None);
889 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
890 assert_eq!(a.downcast_mut::<B>(), None);
892 let a: Box<dyn Error> = Box::new(A);
893 match a.downcast::<B>() {
894 Ok(..) => panic!("expected error"),
895 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),