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.
17 use core::convert::Infallible;
19 use crate::alloc::{AllocErr, LayoutErr};
20 use crate::any::TypeId;
21 use crate::backtrace::Backtrace;
22 use crate::borrow::Cow;
25 use crate::fmt::{self, Debug, Display};
26 use crate::mem::transmute;
31 /// `Error` is a trait representing the basic expectations for error values,
32 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
33 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
34 /// cause chain information:
36 /// The [`source`] method is generally used when errors cross "abstraction
37 /// boundaries". If one module must report an error that is caused by an error
38 /// from a lower-level module, it can allow access to that error via the
39 /// [`source`] method. This makes it possible for the high-level module to
40 /// provide its own errors while also revealing some of the implementation for
41 /// debugging via [`source`] chains.
43 /// [`Result<T, E>`]: Result
44 /// [`source`]: Error::source
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub trait Error: Debug + Display {
47 /// The lower-level source of this error, if any.
52 /// use std::error::Error;
56 /// struct SuperError {
57 /// side: SuperErrorSideKick,
60 /// impl fmt::Display for SuperError {
61 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 /// write!(f, "SuperError is here!")
66 /// impl Error for SuperError {
67 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
73 /// struct SuperErrorSideKick;
75 /// impl fmt::Display for SuperErrorSideKick {
76 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 /// write!(f, "SuperErrorSideKick is here!")
81 /// impl Error for SuperErrorSideKick {}
83 /// fn get_super_error() -> Result<(), SuperError> {
84 /// Err(SuperError { side: SuperErrorSideKick })
88 /// match get_super_error() {
90 /// println!("Error: {}", e);
91 /// println!("Caused by: {}", e.source().unwrap());
93 /// _ => println!("No error"),
97 #[stable(feature = "error_source", since = "1.30.0")]
98 fn source(&self) -> Option<&(dyn Error + 'static)> {
102 /// Gets the `TypeId` of `self`.
105 feature = "error_type_id",
106 reason = "this is memory-unsafe to override in user code",
109 fn type_id(&self, _: private::Internal) -> TypeId
116 /// Returns a stack backtrace, if available, of where this error occurred.
118 /// This function allows inspecting the location, in code, of where an error
119 /// happened. The returned `Backtrace` contains information about the stack
120 /// trace of the OS thread of execution of where the error originated from.
122 /// Note that not all errors contain a `Backtrace`. Also note that a
123 /// `Backtrace` may actually be empty. For more information consult the
124 /// `Backtrace` type itself.
125 #[unstable(feature = "backtrace", issue = "53487")]
126 fn backtrace(&self) -> Option<&Backtrace> {
131 /// if let Err(e) = "xc".parse::<u32>() {
132 /// // Print `e` itself, no need for description().
133 /// eprintln!("Error: {}", e);
136 #[stable(feature = "rust1", since = "1.0.0")]
137 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
138 fn description(&self) -> &str {
139 "description() is deprecated; use Display"
142 #[stable(feature = "rust1", since = "1.0.0")]
145 reason = "replaced by Error::source, which can support downcasting"
147 #[allow(missing_docs)]
148 fn cause(&self) -> Option<&dyn Error> {
154 // This is a hack to prevent `type_id` from being overridden by `Error`
155 // implementations, since that can enable unsound downcasting.
156 #[unstable(feature = "error_type_id", issue = "60784")]
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
163 /// Converts a type of [`Error`] into a box of dyn [`Error`].
168 /// use std::error::Error;
175 /// impl fmt::Display for AnError {
176 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177 /// write!(f , "An error")
181 /// impl Error for AnError {}
183 /// let an_error = AnError;
184 /// assert!(0 == mem::size_of_val(&an_error));
185 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
186 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
188 fn from(err: E) -> Box<dyn Error + 'a> {
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
195 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
196 /// dyn [`Error`] + [`Send`] + [`Sync`].
201 /// use std::error::Error;
208 /// impl fmt::Display for AnError {
209 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210 /// write!(f , "An error")
214 /// impl Error for AnError {}
216 /// unsafe impl Send for AnError {}
218 /// unsafe impl Sync for AnError {}
220 /// let an_error = AnError;
221 /// assert!(0 == mem::size_of_val(&an_error));
222 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
224 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
226 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl From<String> for Box<dyn Error + Send + Sync> {
233 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
238 /// use std::error::Error;
241 /// let a_string_error = "a string error".to_string();
242 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
244 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
247 fn from(err: String) -> Box<dyn Error + Send + Sync> {
248 struct StringError(String);
250 impl Error for StringError {
252 fn description(&self) -> &str {
257 impl Display for StringError {
258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 Display::fmt(&self.0, f)
263 // Purposefully skip printing "StringError(..)"
264 impl Debug for StringError {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 Debug::fmt(&self.0, f)
270 Box::new(StringError(err))
274 #[stable(feature = "string_box_error", since = "1.6.0")]
275 impl From<String> for Box<dyn Error> {
276 /// Converts a [`String`] into a box of dyn [`Error`].
281 /// use std::error::Error;
284 /// let a_string_error = "a string error".to_string();
285 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
286 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
288 fn from(str_err: String) -> Box<dyn Error> {
289 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
290 let err2: Box<dyn Error> = err1;
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
297 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
299 /// [`str`]: prim@str
304 /// use std::error::Error;
307 /// let a_str_error = "a str error";
308 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
310 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
313 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
314 From::from(String::from(err))
318 #[stable(feature = "string_box_error", since = "1.6.0")]
319 impl From<&str> for Box<dyn Error> {
320 /// Converts a [`str`] into a box of dyn [`Error`].
322 /// [`str`]: prim@str
327 /// use std::error::Error;
330 /// let a_str_error = "a str error";
331 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
332 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
334 fn from(err: &str) -> Box<dyn Error> {
335 From::from(String::from(err))
339 #[stable(feature = "cow_box_error", since = "1.22.0")]
340 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
341 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
346 /// use std::error::Error;
348 /// use std::borrow::Cow;
350 /// let a_cow_str_error = Cow::from("a str error");
351 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
353 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
355 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
356 From::from(String::from(err))
360 #[stable(feature = "cow_box_error", since = "1.22.0")]
361 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
362 /// Converts a [`Cow`] into a box of dyn [`Error`].
367 /// use std::error::Error;
369 /// use std::borrow::Cow;
371 /// let a_cow_str_error = Cow::from("a str error");
372 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
373 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
375 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
376 From::from(String::from(err))
380 #[unstable(feature = "never_type", issue = "35121")]
384 feature = "allocator_api",
385 reason = "the precise API and guarantees it provides may be tweaked.",
388 impl Error for AllocErr {}
391 feature = "allocator_api",
392 reason = "the precise API and guarantees it provides may be tweaked.",
395 impl Error for LayoutErr {}
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl Error for str::ParseBoolError {
400 fn description(&self) -> &str {
401 "failed to parse bool"
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl Error for str::Utf8Error {
408 fn description(&self) -> &str {
409 "invalid utf-8: corrupt contents"
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl Error for num::ParseIntError {
416 fn description(&self) -> &str {
421 #[stable(feature = "try_from", since = "1.34.0")]
422 impl Error for num::TryFromIntError {
424 fn description(&self) -> &str {
429 #[stable(feature = "try_from", since = "1.34.0")]
430 impl Error for array::TryFromSliceError {
432 fn description(&self) -> &str {
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl Error for num::ParseFloatError {
440 fn description(&self) -> &str {
445 #[stable(feature = "rust1", since = "1.0.0")]
446 impl Error for string::FromUtf8Error {
448 fn description(&self) -> &str {
453 #[stable(feature = "rust1", since = "1.0.0")]
454 impl Error for string::FromUtf16Error {
456 fn description(&self) -> &str {
461 #[stable(feature = "str_parse_error2", since = "1.8.0")]
462 impl Error for Infallible {
463 fn description(&self) -> &str {
468 #[stable(feature = "decode_utf16", since = "1.9.0")]
469 impl Error for char::DecodeUtf16Error {
471 fn description(&self) -> &str {
472 "unpaired surrogate found"
476 #[stable(feature = "box_error", since = "1.8.0")]
477 impl<T: Error> Error for Box<T> {
478 #[allow(deprecated, deprecated_in_future)]
479 fn description(&self) -> &str {
480 Error::description(&**self)
484 fn cause(&self) -> Option<&dyn Error> {
485 Error::cause(&**self)
488 fn source(&self) -> Option<&(dyn Error + 'static)> {
489 Error::source(&**self)
493 #[stable(feature = "fmt_error", since = "1.11.0")]
494 impl Error for fmt::Error {
496 fn description(&self) -> &str {
497 "an error occurred when formatting an argument"
501 #[stable(feature = "try_borrow", since = "1.13.0")]
502 impl Error for cell::BorrowError {
504 fn description(&self) -> &str {
505 "already mutably borrowed"
509 #[stable(feature = "try_borrow", since = "1.13.0")]
510 impl Error for cell::BorrowMutError {
512 fn description(&self) -> &str {
517 #[stable(feature = "try_from", since = "1.34.0")]
518 impl Error for char::CharTryFromError {
520 fn description(&self) -> &str {
521 "converted integer out of range for `char`"
525 #[stable(feature = "char_from_str", since = "1.20.0")]
526 impl Error for char::ParseCharError {
528 fn description(&self) -> &str {
533 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
534 impl Error for alloc::collections::TryReserveError {}
536 // Copied from `any.rs`.
537 impl dyn Error + 'static {
538 /// Returns `true` if the boxed type is the same as `T`
539 #[stable(feature = "error_downcast", since = "1.3.0")]
541 pub fn is<T: Error + 'static>(&self) -> bool {
542 // Get `TypeId` of the type this function is instantiated with.
543 let t = TypeId::of::<T>();
545 // Get `TypeId` of the type in the trait object.
546 let boxed = self.type_id(private::Internal);
548 // Compare both `TypeId`s on equality.
552 /// Returns some reference to the boxed value if it is of type `T`, or
553 /// `None` if it isn't.
554 #[stable(feature = "error_downcast", since = "1.3.0")]
556 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
558 unsafe { Some(&*(self as *const dyn Error as *const T)) }
564 /// Returns some mutable reference to the boxed value if it is of type `T`, or
565 /// `None` if it isn't.
566 #[stable(feature = "error_downcast", since = "1.3.0")]
568 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
570 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
577 impl dyn Error + 'static + Send {
578 /// Forwards to the method defined on the type `dyn Error`.
579 #[stable(feature = "error_downcast", since = "1.3.0")]
581 pub fn is<T: Error + 'static>(&self) -> bool {
582 <dyn Error + 'static>::is::<T>(self)
585 /// Forwards to the method defined on the type `dyn Error`.
586 #[stable(feature = "error_downcast", since = "1.3.0")]
588 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
589 <dyn Error + 'static>::downcast_ref::<T>(self)
592 /// Forwards to the method defined on the type `dyn Error`.
593 #[stable(feature = "error_downcast", since = "1.3.0")]
595 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
596 <dyn Error + 'static>::downcast_mut::<T>(self)
600 impl dyn Error + 'static + Send + Sync {
601 /// Forwards to the method defined on the type `dyn Error`.
602 #[stable(feature = "error_downcast", since = "1.3.0")]
604 pub fn is<T: Error + 'static>(&self) -> bool {
605 <dyn Error + 'static>::is::<T>(self)
608 /// Forwards to the method defined on the type `dyn Error`.
609 #[stable(feature = "error_downcast", since = "1.3.0")]
611 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
612 <dyn Error + 'static>::downcast_ref::<T>(self)
615 /// Forwards to the method defined on the type `dyn Error`.
616 #[stable(feature = "error_downcast", since = "1.3.0")]
618 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
619 <dyn Error + 'static>::downcast_mut::<T>(self)
625 #[stable(feature = "error_downcast", since = "1.3.0")]
626 /// Attempts to downcast the box to a concrete type.
627 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
630 let raw: *mut dyn Error = Box::into_raw(self);
631 Ok(Box::from_raw(raw as *mut T))
638 /// Returns an iterator starting with the current error and continuing with
639 /// recursively calling [`source`].
641 /// If you want to omit the current error and only use its sources,
647 /// #![feature(error_iter)]
648 /// use std::error::Error;
655 /// struct B(Option<Box<dyn Error + 'static>>);
657 /// impl fmt::Display for A {
658 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 /// impl fmt::Display for B {
664 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
669 /// impl Error for A {}
671 /// impl Error for B {
672 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
673 /// self.0.as_ref().map(|e| e.as_ref())
677 /// let b = B(Some(Box::new(A)));
679 /// // let err : Box<Error> = b.into(); // or
680 /// let err = &b as &(dyn Error);
682 /// let mut iter = err.chain();
684 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
685 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
686 /// assert!(iter.next().is_none());
687 /// assert!(iter.next().is_none());
690 /// [`source`]: Error::source
691 #[unstable(feature = "error_iter", issue = "58520")]
693 pub fn chain(&self) -> Chain<'_> {
694 Chain { current: Some(self) }
698 /// An iterator over an [`Error`] and its sources.
700 /// If you want to omit the initial error and only process
701 /// its sources, use `skip(1)`.
702 #[unstable(feature = "error_iter", issue = "58520")]
703 #[derive(Clone, Debug)]
704 pub struct Chain<'a> {
705 current: Option<&'a (dyn Error + 'static)>,
708 #[unstable(feature = "error_iter", issue = "58520")]
709 impl<'a> Iterator for Chain<'a> {
710 type Item = &'a (dyn Error + 'static);
712 fn next(&mut self) -> Option<Self::Item> {
713 let current = self.current;
714 self.current = self.current.and_then(Error::source);
719 impl dyn Error + Send {
721 #[stable(feature = "error_downcast", since = "1.3.0")]
722 /// Attempts to downcast the box to a concrete type.
723 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
724 let err: Box<dyn Error> = self;
725 <dyn Error>::downcast(err).map_err(|s| unsafe {
726 // Reapply the `Send` marker.
727 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
732 impl dyn Error + Send + Sync {
734 #[stable(feature = "error_downcast", since = "1.3.0")]
735 /// Attempts to downcast the box to a concrete type.
736 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
737 let err: Box<dyn Error> = self;
738 <dyn Error>::downcast(err).map_err(|s| unsafe {
739 // Reapply the `Send + Sync` marker.
740 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
750 #[derive(Debug, PartialEq)]
752 #[derive(Debug, PartialEq)]
755 impl fmt::Display for A {
756 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
760 impl fmt::Display for B {
761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 let a = &mut a as &mut (dyn Error + 'static);
773 assert_eq!(a.downcast_ref::<A>(), Some(&A));
774 assert_eq!(a.downcast_ref::<B>(), None);
775 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
776 assert_eq!(a.downcast_mut::<B>(), None);
778 let a: Box<dyn Error> = Box::new(A);
779 match a.downcast::<B>() {
780 Ok(..) => panic!("expected error"),
781 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),