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, CannotReallocInPlace, LayoutErr};
19 use crate::any::TypeId;
20 use crate::backtrace::Backtrace;
21 use crate::borrow::Cow;
24 use crate::fmt::{self, Debug, Display};
25 use crate::mem::transmute;
30 /// `Error` is a trait representing the basic expectations for error values,
31 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
32 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
33 /// cause chain information:
35 /// The [`source`] method is generally used when errors cross "abstraction
36 /// boundaries". If one module must report an error that is caused by an error
37 /// from a lower-level module, it can allow access to that error via the
38 /// [`source`] method. This makes it possible for the high-level module to
39 /// provide its own errors while also revealing some of the implementation for
40 /// debugging via [`source`] chains.
42 /// [`Result<T, E>`]: ../result/enum.Result.html
43 /// [`Display`]: ../fmt/trait.Display.html
44 /// [`Debug`]: ../fmt/trait.Debug.html
45 /// [`source`]: trait.Error.html#method.source
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub trait Error: Debug + Display {
48 /// **This method is soft-deprecated.**
50 /// Although using it won’t cause compilation warning,
51 /// new code should use [`Display`] instead
52 /// and new `impl`s can omit it.
54 /// To obtain error description as a string, use `to_string()`.
56 /// [`Display`]: ../fmt/trait.Display.html
61 /// match "xc".parse::<u32>() {
63 /// // Print `e` itself, not `e.description()`.
64 /// println!("Error: {}", e);
66 /// _ => println!("No error"),
69 #[stable(feature = "rust1", since = "1.0.0")]
70 fn description(&self) -> &str {
71 "description() is deprecated; use Display"
74 /// The lower-level cause of this error, if any.
79 /// use std::error::Error;
83 /// struct SuperError {
84 /// side: SuperErrorSideKick,
87 /// impl fmt::Display for SuperError {
88 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 /// write!(f, "SuperError is here!")
93 /// impl Error for SuperError {
94 /// fn cause(&self) -> Option<&dyn Error> {
100 /// struct SuperErrorSideKick;
102 /// impl fmt::Display for SuperErrorSideKick {
103 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 /// write!(f, "SuperErrorSideKick is here!")
108 /// impl Error for SuperErrorSideKick {}
110 /// fn get_super_error() -> Result<(), SuperError> {
111 /// Err(SuperError { side: SuperErrorSideKick })
115 /// match get_super_error() {
117 /// println!("Error: {}", e.description());
118 /// println!("Caused by: {}", e.cause().unwrap());
120 /// _ => println!("No error"),
124 #[stable(feature = "rust1", since = "1.0.0")]
127 reason = "replaced by Error::source, which can support \
130 fn cause(&self) -> Option<&dyn Error> {
134 /// The lower-level source of this error, if any.
139 /// use std::error::Error;
143 /// struct SuperError {
144 /// side: SuperErrorSideKick,
147 /// impl fmt::Display for SuperError {
148 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 /// write!(f, "SuperError is here!")
153 /// impl Error for SuperError {
154 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
160 /// struct SuperErrorSideKick;
162 /// impl fmt::Display for SuperErrorSideKick {
163 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 /// write!(f, "SuperErrorSideKick is here!")
168 /// impl Error for SuperErrorSideKick {}
170 /// fn get_super_error() -> Result<(), SuperError> {
171 /// Err(SuperError { side: SuperErrorSideKick })
175 /// match get_super_error() {
177 /// println!("Error: {}", e.description());
178 /// println!("Caused by: {}", e.source().unwrap());
180 /// _ => println!("No error"),
184 #[stable(feature = "error_source", since = "1.30.0")]
185 fn source(&self) -> Option<&(dyn Error + 'static)> {
189 /// Gets the `TypeId` of `self`.
192 feature = "error_type_id",
193 reason = "this is memory-unsafe to override in user code",
196 fn type_id(&self, _: private::Internal) -> TypeId
203 /// Returns a stack backtrace, if available, of where this error occurred.
205 /// This function allows inspecting the location, in code, of where an error
206 /// happened. The returned `Backtrace` contains information about the stack
207 /// trace of the OS thread of execution of where the error originated from.
209 /// Note that not all errors contain a `Backtrace`. Also note that a
210 /// `Backtrace` may actually be empty. For more information consult the
211 /// `Backtrace` type itself.
212 #[unstable(feature = "backtrace", issue = "53487")]
213 fn backtrace(&self) -> Option<&Backtrace> {
219 // This is a hack to prevent `type_id` from being overridden by `Error`
220 // implementations, since that can enable unsound downcasting.
221 #[unstable(feature = "error_type_id", issue = "60784")]
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
228 /// Converts a type of [`Error`] into a box of dyn [`Error`].
230 /// [`Error`]: ../error/trait.Error.html
235 /// use std::error::Error;
242 /// impl fmt::Display for AnError {
243 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 /// write!(f , "An error")
248 /// impl Error for AnError {}
250 /// let an_error = AnError;
251 /// assert!(0 == mem::size_of_val(&an_error));
252 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
253 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
255 fn from(err: E) -> Box<dyn Error + 'a> {
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
262 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
263 /// dyn [`Error`] + [`Send`] + [`Sync`].
265 /// [`Error`]: ../error/trait.Error.html
270 /// use std::error::Error;
277 /// impl fmt::Display for AnError {
278 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 /// write!(f , "An error")
283 /// impl Error for AnError {}
285 /// unsafe impl Send for AnError {}
287 /// unsafe impl Sync for AnError {}
289 /// let an_error = AnError;
290 /// assert!(0 == mem::size_of_val(&an_error));
291 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
293 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
295 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl From<String> for Box<dyn Error + Send + Sync> {
302 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
304 /// [`Error`]: ../error/trait.Error.html
309 /// use std::error::Error;
312 /// let a_string_error = "a string error".to_string();
313 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
315 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
317 fn from(err: String) -> Box<dyn Error + Send + Sync> {
318 struct StringError(String);
320 impl Error for StringError {
321 fn description(&self) -> &str {
326 impl Display for StringError {
327 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
328 Display::fmt(&self.0, f)
332 // Purposefully skip printing "StringError(..)"
333 impl Debug for StringError {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 Debug::fmt(&self.0, f)
339 Box::new(StringError(err))
343 #[stable(feature = "string_box_error", since = "1.6.0")]
344 impl From<String> for Box<dyn Error> {
345 /// Converts a [`String`] into a box of dyn [`Error`].
347 /// [`Error`]: ../error/trait.Error.html
352 /// use std::error::Error;
355 /// let a_string_error = "a string error".to_string();
356 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
357 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
359 fn from(str_err: String) -> Box<dyn Error> {
360 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
361 let err2: Box<dyn Error> = err1;
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
368 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
370 /// [`Error`]: ../error/trait.Error.html
375 /// use std::error::Error;
378 /// let a_str_error = "a str error";
379 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
381 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
383 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
384 From::from(String::from(err))
388 #[stable(feature = "string_box_error", since = "1.6.0")]
389 impl From<&str> for Box<dyn Error> {
390 /// Converts a [`str`] into a box of dyn [`Error`].
392 /// [`Error`]: ../error/trait.Error.html
397 /// use std::error::Error;
400 /// let a_str_error = "a str error";
401 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
402 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
404 fn from(err: &str) -> Box<dyn Error> {
405 From::from(String::from(err))
409 #[stable(feature = "cow_box_error", since = "1.22.0")]
410 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
411 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
413 /// [`Cow`]: ../borrow/enum.Cow.html
414 /// [`Error`]: ../error/trait.Error.html
419 /// use std::error::Error;
421 /// use std::borrow::Cow;
423 /// let a_cow_str_error = Cow::from("a str error");
424 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
426 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
428 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
429 From::from(String::from(err))
433 #[stable(feature = "cow_box_error", since = "1.22.0")]
434 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
435 /// Converts a [`Cow`] into a box of dyn [`Error`].
437 /// [`Cow`]: ../borrow/enum.Cow.html
438 /// [`Error`]: ../error/trait.Error.html
443 /// use std::error::Error;
445 /// use std::borrow::Cow;
447 /// let a_cow_str_error = Cow::from("a str error");
448 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
449 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
451 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
452 From::from(String::from(err))
456 #[unstable(feature = "never_type", issue = "35121")]
458 fn description(&self) -> &str {
464 feature = "allocator_api",
465 reason = "the precise API and guarantees it provides may be tweaked.",
468 impl Error for AllocErr {
469 fn description(&self) -> &str {
470 "memory allocation failed"
475 feature = "allocator_api",
476 reason = "the precise API and guarantees it provides may be tweaked.",
479 impl Error for LayoutErr {
480 fn description(&self) -> &str {
481 "invalid parameters to Layout::from_size_align"
486 feature = "allocator_api",
487 reason = "the precise API and guarantees it provides may be tweaked.",
490 impl Error for CannotReallocInPlace {
491 fn description(&self) -> &str {
492 CannotReallocInPlace::description(self)
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl Error for str::ParseBoolError {
498 fn description(&self) -> &str {
499 "failed to parse bool"
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl Error for str::Utf8Error {
505 fn description(&self) -> &str {
506 "invalid utf-8: corrupt contents"
510 #[stable(feature = "rust1", since = "1.0.0")]
511 impl Error for num::ParseIntError {
512 fn description(&self) -> &str {
517 #[stable(feature = "try_from", since = "1.34.0")]
518 impl Error for num::TryFromIntError {
519 fn description(&self) -> &str {
524 #[stable(feature = "try_from", since = "1.34.0")]
525 impl Error for array::TryFromSliceError {
526 fn description(&self) -> &str {
531 #[stable(feature = "rust1", since = "1.0.0")]
532 impl Error for num::ParseFloatError {
533 fn description(&self) -> &str {
538 #[stable(feature = "rust1", since = "1.0.0")]
539 impl Error for string::FromUtf8Error {
540 fn description(&self) -> &str {
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl Error for string::FromUtf16Error {
547 fn description(&self) -> &str {
552 #[stable(feature = "str_parse_error2", since = "1.8.0")]
553 impl Error for string::ParseError {
554 fn description(&self) -> &str {
559 #[stable(feature = "decode_utf16", since = "1.9.0")]
560 impl Error for char::DecodeUtf16Error {
561 fn description(&self) -> &str {
562 "unpaired surrogate found"
566 #[stable(feature = "box_error", since = "1.8.0")]
567 impl<T: Error> Error for Box<T> {
568 fn description(&self) -> &str {
569 Error::description(&**self)
573 fn cause(&self) -> Option<&dyn Error> {
574 Error::cause(&**self)
577 fn source(&self) -> Option<&(dyn Error + 'static)> {
578 Error::source(&**self)
582 #[stable(feature = "fmt_error", since = "1.11.0")]
583 impl Error for fmt::Error {
584 fn description(&self) -> &str {
585 "an error occurred when formatting an argument"
589 #[stable(feature = "try_borrow", since = "1.13.0")]
590 impl Error for cell::BorrowError {
591 fn description(&self) -> &str {
592 "already mutably borrowed"
596 #[stable(feature = "try_borrow", since = "1.13.0")]
597 impl Error for cell::BorrowMutError {
598 fn description(&self) -> &str {
603 #[stable(feature = "try_from", since = "1.34.0")]
604 impl Error for char::CharTryFromError {
605 fn description(&self) -> &str {
606 "converted integer out of range for `char`"
610 #[stable(feature = "char_from_str", since = "1.20.0")]
611 impl Error for char::ParseCharError {
612 fn description(&self) -> &str {
617 // Copied from `any.rs`.
618 impl dyn Error + 'static {
619 /// Returns `true` if the boxed type is the same as `T`
620 #[stable(feature = "error_downcast", since = "1.3.0")]
622 pub fn is<T: Error + 'static>(&self) -> bool {
623 // Get `TypeId` of the type this function is instantiated with.
624 let t = TypeId::of::<T>();
626 // Get `TypeId` of the type in the trait object.
627 let boxed = self.type_id(private::Internal);
629 // Compare both `TypeId`s on equality.
633 /// Returns some reference to the boxed value if it is of type `T`, or
634 /// `None` if it isn't.
635 #[stable(feature = "error_downcast", since = "1.3.0")]
637 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
639 unsafe { Some(&*(self as *const dyn Error as *const T)) }
645 /// Returns some mutable reference to the boxed value if it is of type `T`, or
646 /// `None` if it isn't.
647 #[stable(feature = "error_downcast", since = "1.3.0")]
649 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
651 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
658 impl dyn Error + 'static + Send {
659 /// Forwards to the method defined on the type `dyn Error`.
660 #[stable(feature = "error_downcast", since = "1.3.0")]
662 pub fn is<T: Error + 'static>(&self) -> bool {
663 <dyn Error + 'static>::is::<T>(self)
666 /// Forwards to the method defined on the type `dyn Error`.
667 #[stable(feature = "error_downcast", since = "1.3.0")]
669 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
670 <dyn Error + 'static>::downcast_ref::<T>(self)
673 /// Forwards to the method defined on the type `dyn Error`.
674 #[stable(feature = "error_downcast", since = "1.3.0")]
676 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
677 <dyn Error + 'static>::downcast_mut::<T>(self)
681 impl dyn Error + 'static + Send + Sync {
682 /// Forwards to the method defined on the type `dyn Error`.
683 #[stable(feature = "error_downcast", since = "1.3.0")]
685 pub fn is<T: Error + 'static>(&self) -> bool {
686 <dyn Error + 'static>::is::<T>(self)
689 /// Forwards to the method defined on the type `dyn Error`.
690 #[stable(feature = "error_downcast", since = "1.3.0")]
692 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
693 <dyn Error + 'static>::downcast_ref::<T>(self)
696 /// Forwards to the method defined on the type `dyn Error`.
697 #[stable(feature = "error_downcast", since = "1.3.0")]
699 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
700 <dyn Error + 'static>::downcast_mut::<T>(self)
706 #[stable(feature = "error_downcast", since = "1.3.0")]
707 /// Attempts to downcast the box to a concrete type.
708 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
711 let raw: *mut dyn Error = Box::into_raw(self);
712 Ok(Box::from_raw(raw as *mut T))
719 /// Returns an iterator starting with the current error and continuing with
720 /// recursively calling [`source`].
722 /// If you want to omit the current error and only use its sources,
728 /// #![feature(error_iter)]
729 /// use std::error::Error;
736 /// struct B(Option<Box<dyn Error + 'static>>);
738 /// impl fmt::Display for A {
739 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
744 /// impl fmt::Display for B {
745 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
750 /// impl Error for A {}
752 /// impl Error for B {
753 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
754 /// self.0.as_ref().map(|e| e.as_ref())
758 /// let b = B(Some(Box::new(A)));
760 /// // let err : Box<Error> = b.into(); // or
761 /// let err = &b as &(dyn Error);
763 /// let mut iter = err.chain();
765 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
766 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
767 /// assert!(iter.next().is_none());
768 /// assert!(iter.next().is_none());
771 /// [`source`]: trait.Error.html#method.source
772 #[unstable(feature = "error_iter", issue = "58520")]
774 pub fn chain(&self) -> Chain<'_> {
775 Chain { current: Some(self) }
779 /// An iterator over an [`Error`] and its sources.
781 /// If you want to omit the initial error and only process
782 /// its sources, use `skip(1)`.
784 /// [`Error`]: trait.Error.html
785 #[unstable(feature = "error_iter", issue = "58520")]
786 #[derive(Clone, Debug)]
787 pub struct Chain<'a> {
788 current: Option<&'a (dyn Error + 'static)>,
791 #[unstable(feature = "error_iter", issue = "58520")]
792 impl<'a> Iterator for Chain<'a> {
793 type Item = &'a (dyn Error + 'static);
795 fn next(&mut self) -> Option<Self::Item> {
796 let current = self.current;
797 self.current = self.current.and_then(Error::source);
802 impl dyn Error + Send {
804 #[stable(feature = "error_downcast", since = "1.3.0")]
805 /// Attempts to downcast the box to a concrete type.
806 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
807 let err: Box<dyn Error> = self;
808 <dyn Error>::downcast(err).map_err(|s| unsafe {
809 // Reapply the `Send` marker.
810 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
815 impl dyn Error + Send + Sync {
817 #[stable(feature = "error_downcast", since = "1.3.0")]
818 /// Attempts to downcast the box to a concrete type.
819 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
820 let err: Box<dyn Error> = self;
821 <dyn Error>::downcast(err).map_err(|s| unsafe {
822 // Reapply the `Send + Sync` marker.
823 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
833 #[derive(Debug, PartialEq)]
835 #[derive(Debug, PartialEq)]
838 impl fmt::Display for A {
839 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
843 impl fmt::Display for B {
844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
850 fn description(&self) -> &str {
855 fn description(&self) -> &str {
863 let a = &mut a as &mut (dyn Error + 'static);
864 assert_eq!(a.downcast_ref::<A>(), Some(&A));
865 assert_eq!(a.downcast_ref::<B>(), None);
866 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
867 assert_eq!(a.downcast_mut::<B>(), None);
869 let a: Box<dyn Error> = Box::new(A);
870 match a.downcast::<B>() {
871 Ok(..) => panic!("expected error"),
872 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),