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 #[stable(feature = "error_type_id", since = "1.34.0")]
202 fn type_id(&self) -> TypeId where Self: 'static {
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
209 /// Converts a type of [`Error`] into a box of dyn [`Error`].
214 /// use std::error::Error;
221 /// impl fmt::Display for AnError {
222 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 /// write!(f , "An error")
227 /// impl Error for AnError {
228 /// fn description(&self) -> &str {
229 /// "Description of an error"
233 /// let an_error = AnError;
234 /// assert!(0 == mem::size_of_val(&an_error));
235 /// let a_boxed_error = Box::<Error>::from(an_error);
236 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
238 fn from(err: E) -> Box<dyn Error + 'a> {
243 #[stable(feature = "rust1", since = "1.0.0")]
244 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
245 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
246 /// [`Send`] + [`Sync`].
251 /// use std::error::Error;
258 /// impl fmt::Display for AnError {
259 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
260 /// write!(f , "An error")
264 /// impl Error for AnError {
265 /// fn description(&self) -> &str {
266 /// "Description of an error"
270 /// unsafe impl Send for AnError {}
272 /// unsafe impl Sync for AnError {}
274 /// let an_error = AnError;
275 /// assert!(0 == mem::size_of_val(&an_error));
276 /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
278 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
280 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl From<String> for Box<dyn Error + Send + Sync> {
287 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
292 /// use std::error::Error;
295 /// let a_string_error = "a string error".to_string();
296 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
298 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
300 fn from(err: String) -> Box<dyn Error + Send + Sync> {
302 struct StringError(String);
304 impl Error for StringError {
305 fn description(&self) -> &str { &self.0 }
308 impl Display for StringError {
309 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
310 Display::fmt(&self.0, f)
314 Box::new(StringError(err))
318 #[stable(feature = "string_box_error", since = "1.6.0")]
319 impl From<String> for Box<dyn Error> {
320 /// Converts a [`String`] into a box of dyn [`Error`].
325 /// use std::error::Error;
328 /// let a_string_error = "a string error".to_string();
329 /// let a_boxed_error = Box::<Error>::from(a_string_error);
330 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
332 fn from(str_err: String) -> Box<dyn Error> {
333 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
334 let err2: Box<dyn Error> = err1;
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
341 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
346 /// use std::error::Error;
349 /// let a_str_error = "a str error";
350 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
352 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
354 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
355 From::from(String::from(err))
359 #[stable(feature = "string_box_error", since = "1.6.0")]
360 impl From<&str> for Box<dyn Error> {
361 /// Converts a [`str`] into a box of dyn [`Error`].
366 /// use std::error::Error;
369 /// let a_str_error = "a str error";
370 /// let a_boxed_error = Box::<Error>::from(a_str_error);
371 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
373 fn from(err: &str) -> Box<dyn Error> {
374 From::from(String::from(err))
378 #[stable(feature = "cow_box_error", since = "1.22.0")]
379 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
380 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
385 /// use std::error::Error;
387 /// use std::borrow::Cow;
389 /// let a_cow_str_error = Cow::from("a str error");
390 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
392 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
394 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
395 From::from(String::from(err))
399 #[stable(feature = "cow_box_error", since = "1.22.0")]
400 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
401 /// Converts a [`Cow`] into a box of dyn [`Error`].
406 /// use std::error::Error;
408 /// use std::borrow::Cow;
410 /// let a_cow_str_error = Cow::from("a str error");
411 /// let a_boxed_error = Box::<Error>::from(a_cow_str_error);
412 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
414 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
415 From::from(String::from(err))
419 #[unstable(feature = "never_type", issue = "35121")]
421 fn description(&self) -> &str { *self }
424 #[unstable(feature = "allocator_api",
425 reason = "the precise API and guarantees it provides may be tweaked.",
427 impl Error for AllocErr {
428 fn description(&self) -> &str {
429 "memory allocation failed"
433 #[unstable(feature = "allocator_api",
434 reason = "the precise API and guarantees it provides may be tweaked.",
436 impl Error for LayoutErr {
437 fn description(&self) -> &str {
438 "invalid parameters to Layout::from_size_align"
442 #[unstable(feature = "allocator_api",
443 reason = "the precise API and guarantees it provides may be tweaked.",
445 impl Error for CannotReallocInPlace {
446 fn description(&self) -> &str {
447 CannotReallocInPlace::description(self)
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl Error for str::ParseBoolError {
453 fn description(&self) -> &str { "failed to parse bool" }
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl Error for str::Utf8Error {
458 fn description(&self) -> &str {
459 "invalid utf-8: corrupt contents"
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl Error for num::ParseIntError {
465 fn description(&self) -> &str {
470 #[stable(feature = "try_from", since = "1.34.0")]
471 impl Error for num::TryFromIntError {
472 fn description(&self) -> &str {
477 #[stable(feature = "try_from", since = "1.34.0")]
478 impl Error for array::TryFromSliceError {
479 fn description(&self) -> &str {
484 #[stable(feature = "rust1", since = "1.0.0")]
485 impl Error for num::ParseFloatError {
486 fn description(&self) -> &str {
491 #[stable(feature = "rust1", since = "1.0.0")]
492 impl Error for string::FromUtf8Error {
493 fn description(&self) -> &str {
498 #[stable(feature = "rust1", since = "1.0.0")]
499 impl Error for string::FromUtf16Error {
500 fn description(&self) -> &str {
505 #[stable(feature = "str_parse_error2", since = "1.8.0")]
506 impl Error for string::ParseError {
507 fn description(&self) -> &str {
512 #[stable(feature = "decode_utf16", since = "1.9.0")]
513 impl Error for char::DecodeUtf16Error {
514 fn description(&self) -> &str {
515 "unpaired surrogate found"
519 #[stable(feature = "box_error", since = "1.8.0")]
520 impl<T: Error> Error for Box<T> {
521 fn description(&self) -> &str {
522 Error::description(&**self)
526 fn cause(&self) -> Option<&dyn Error> {
527 Error::cause(&**self)
531 #[stable(feature = "fmt_error", since = "1.11.0")]
532 impl Error for fmt::Error {
533 fn description(&self) -> &str {
534 "an error occurred when formatting an argument"
538 #[stable(feature = "try_borrow", since = "1.13.0")]
539 impl Error for cell::BorrowError {
540 fn description(&self) -> &str {
541 "already mutably borrowed"
545 #[stable(feature = "try_borrow", since = "1.13.0")]
546 impl Error for cell::BorrowMutError {
547 fn description(&self) -> &str {
552 #[stable(feature = "try_from", since = "1.34.0")]
553 impl Error for char::CharTryFromError {
554 fn description(&self) -> &str {
555 "converted integer out of range for `char`"
559 #[stable(feature = "char_from_str", since = "1.20.0")]
560 impl Error for char::ParseCharError {
561 fn description(&self) -> &str {
566 // copied from any.rs
567 impl dyn Error + 'static {
568 /// Returns `true` if the boxed type is the same as `T`
569 #[stable(feature = "error_downcast", since = "1.3.0")]
571 pub fn is<T: Error + 'static>(&self) -> bool {
572 // Get TypeId of the type this function is instantiated with
573 let t = TypeId::of::<T>();
575 // Get TypeId of the type in the trait object
576 let boxed = self.type_id();
578 // Compare both TypeIds on equality
582 /// Returns some reference to the boxed value if it is of type `T`, or
583 /// `None` if it isn't.
584 #[stable(feature = "error_downcast", since = "1.3.0")]
586 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
589 Some(&*(self as *const dyn Error as *const T))
596 /// Returns some mutable reference to the boxed value if it is of type `T`, or
597 /// `None` if it isn't.
598 #[stable(feature = "error_downcast", since = "1.3.0")]
600 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
603 Some(&mut *(self as *mut dyn Error as *mut T))
611 impl dyn Error + 'static + Send {
612 /// Forwards to the method defined on the type `Any`.
613 #[stable(feature = "error_downcast", since = "1.3.0")]
615 pub fn is<T: Error + 'static>(&self) -> bool {
616 <dyn Error + 'static>::is::<T>(self)
619 /// Forwards to the method defined on the type `Any`.
620 #[stable(feature = "error_downcast", since = "1.3.0")]
622 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
623 <dyn Error + 'static>::downcast_ref::<T>(self)
626 /// Forwards to the method defined on the type `Any`.
627 #[stable(feature = "error_downcast", since = "1.3.0")]
629 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
630 <dyn Error + 'static>::downcast_mut::<T>(self)
634 impl dyn Error + 'static + Send + Sync {
635 /// Forwards to the method defined on the type `Any`.
636 #[stable(feature = "error_downcast", since = "1.3.0")]
638 pub fn is<T: Error + 'static>(&self) -> bool {
639 <dyn Error + 'static>::is::<T>(self)
642 /// Forwards to the method defined on the type `Any`.
643 #[stable(feature = "error_downcast", since = "1.3.0")]
645 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
646 <dyn Error + 'static>::downcast_ref::<T>(self)
649 /// Forwards to the method defined on the type `Any`.
650 #[stable(feature = "error_downcast", since = "1.3.0")]
652 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
653 <dyn Error + 'static>::downcast_mut::<T>(self)
659 #[stable(feature = "error_downcast", since = "1.3.0")]
660 /// Attempt to downcast the box to a concrete type.
661 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
664 let raw: *mut dyn Error = Box::into_raw(self);
665 Ok(Box::from_raw(raw as *mut T))
672 /// Returns an iterator starting with the current error and continuing with
673 /// recursively calling [`source`].
678 /// #![feature(error_iter)]
679 /// use std::error::Error;
686 /// struct B(Option<Box<dyn Error + 'static>>);
688 /// impl fmt::Display for A {
689 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
694 /// impl fmt::Display for B {
695 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
700 /// impl Error for A {}
702 /// impl Error for B {
703 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
704 /// self.0.as_ref().map(|e| e.as_ref())
708 /// let b = B(Some(Box::new(A)));
710 /// // let err : Box<Error> = b.into(); // or
711 /// let err = &b as &(dyn Error);
713 /// let mut iter = err.iter_chain();
715 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
716 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
717 /// assert!(iter.next().is_none());
718 /// assert!(iter.next().is_none());
721 /// [`source`]: trait.Error.html#method.source
722 #[unstable(feature = "error_iter", issue = "58520")]
724 pub fn iter_chain(&self) -> ErrorIter {
730 /// Returns an iterator starting with the [`source`] of this error
731 /// and continuing with recursively calling [`source`].
736 /// #![feature(error_iter)]
737 /// use std::error::Error;
744 /// struct B(Option<Box<dyn Error + 'static>>);
747 /// struct C(Option<Box<dyn Error + 'static>>);
749 /// impl fmt::Display for A {
750 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
755 /// impl fmt::Display for B {
756 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
761 /// impl fmt::Display for C {
762 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
767 /// impl Error for A {}
769 /// impl Error for B {
770 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
771 /// self.0.as_ref().map(|e| e.as_ref())
775 /// impl Error for C {
776 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
777 /// self.0.as_ref().map(|e| e.as_ref())
781 /// let b = B(Some(Box::new(A)));
782 /// let c = C(Some(Box::new(b)));
784 /// // let err : Box<Error> = c.into(); // or
785 /// let err = &c as &(dyn Error);
787 /// let mut iter = err.iter_sources();
789 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
790 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
791 /// assert!(iter.next().is_none());
792 /// assert!(iter.next().is_none());
795 /// [`source`]: trait.Error.html#method.source
797 #[unstable(feature = "error_iter", issue = "58520")]
798 pub fn iter_sources(&self) -> ErrorIter {
800 current: self.source(),
805 /// An iterator over [`Error`]
807 /// [`Error`]: trait.Error.html
808 #[unstable(feature = "error_iter", issue = "58520")]
809 #[derive(Copy, Clone, Debug)]
810 pub struct ErrorIter<'a> {
811 current: Option<&'a (dyn Error + 'static)>,
814 #[unstable(feature = "error_iter", issue = "58520")]
815 impl<'a> Iterator for ErrorIter<'a> {
816 type Item = &'a (dyn Error + 'static);
818 fn next(&mut self) -> Option<Self::Item> {
819 let current = self.current;
820 self.current = self.current.and_then(Error::source);
825 impl dyn Error + Send {
827 #[stable(feature = "error_downcast", since = "1.3.0")]
828 /// Attempt to downcast the box to a concrete type.
829 pub fn downcast<T: Error + 'static>(self: Box<Self>)
830 -> Result<Box<T>, Box<dyn Error + Send>> {
831 let err: Box<dyn Error> = self;
832 <dyn Error>::downcast(err).map_err(|s| unsafe {
833 // reapply the Send marker
834 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
839 impl dyn Error + Send + Sync {
841 #[stable(feature = "error_downcast", since = "1.3.0")]
842 /// Attempt to downcast the box to a concrete type.
843 pub fn downcast<T: Error + 'static>(self: Box<Self>)
844 -> Result<Box<T>, Box<Self>> {
845 let err: Box<dyn Error> = self;
846 <dyn Error>::downcast(err).map_err(|s| unsafe {
847 // reapply the Send+Sync marker
848 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
858 #[derive(Debug, PartialEq)]
860 #[derive(Debug, PartialEq)]
863 impl fmt::Display for A {
864 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
868 impl fmt::Display for B {
869 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
875 fn description(&self) -> &str { "A-desc" }
878 fn description(&self) -> &str { "A-desc" }
884 let a = &mut a as &mut (dyn Error + 'static);
885 assert_eq!(a.downcast_ref::<A>(), Some(&A));
886 assert_eq!(a.downcast_ref::<B>(), None);
887 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
888 assert_eq!(a.downcast_mut::<B>(), None);
890 let a: Box<dyn Error> = Box::new(A);
891 match a.downcast::<B>() {
892 Ok(..) => panic!("expected error"),
893 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),