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.
20 use core::convert::Infallible;
22 use crate::alloc::{AllocError, LayoutError};
23 use crate::any::TypeId;
24 use crate::backtrace::Backtrace;
25 use crate::borrow::Cow;
28 use crate::fmt::{self, Debug, Display};
29 use crate::mem::transmute;
35 /// `Error` is a trait representing the basic expectations for error values,
36 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
37 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
38 /// cause chain information:
40 /// [`Error::source()`] is generally used when errors cross
41 /// "abstraction boundaries". If one module must report an error that is caused
42 /// by an error from a lower-level module, it can allow accessing that error
43 /// via [`Error::source()`]. This makes it possible for the high-level
44 /// module to provide its own errors while also revealing some of the
45 /// implementation for debugging via `source` chains.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub trait Error: Debug + Display {
48 /// The lower-level source of this error, if any.
53 /// use std::error::Error;
57 /// struct SuperError {
58 /// side: SuperErrorSideKick,
61 /// impl fmt::Display for SuperError {
62 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 /// write!(f, "SuperError is here!")
67 /// impl Error for SuperError {
68 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
74 /// struct SuperErrorSideKick;
76 /// impl fmt::Display for SuperErrorSideKick {
77 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 /// write!(f, "SuperErrorSideKick is here!")
82 /// impl Error for SuperErrorSideKick {}
84 /// fn get_super_error() -> Result<(), SuperError> {
85 /// Err(SuperError { side: SuperErrorSideKick })
89 /// match get_super_error() {
91 /// println!("Error: {}", e);
92 /// println!("Caused by: {}", e.source().unwrap());
94 /// _ => println!("No error"),
98 #[stable(feature = "error_source", since = "1.30.0")]
99 fn source(&self) -> Option<&(dyn Error + 'static)> {
103 /// Gets the `TypeId` of `self`.
106 feature = "error_type_id",
107 reason = "this is memory-unsafe to override in user code",
110 fn type_id(&self, _: private::Internal) -> TypeId
117 /// Returns a stack backtrace, if available, of where this error occurred.
119 /// This function allows inspecting the location, in code, of where an error
120 /// happened. The returned `Backtrace` contains information about the stack
121 /// trace of the OS thread of execution of where the error originated from.
123 /// Note that not all errors contain a `Backtrace`. Also note that a
124 /// `Backtrace` may actually be empty. For more information consult the
125 /// `Backtrace` type itself.
126 #[unstable(feature = "backtrace", issue = "53487")]
127 fn backtrace(&self) -> Option<&Backtrace> {
132 /// if let Err(e) = "xc".parse::<u32>() {
133 /// // Print `e` itself, no need for description().
134 /// eprintln!("Error: {}", e);
137 #[stable(feature = "rust1", since = "1.0.0")]
138 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
139 fn description(&self) -> &str {
140 "description() is deprecated; use Display"
143 #[stable(feature = "rust1", since = "1.0.0")]
146 reason = "replaced by Error::source, which can support downcasting"
148 #[allow(missing_docs)]
149 fn cause(&self) -> Option<&dyn Error> {
155 // This is a hack to prevent `type_id` from being overridden by `Error`
156 // implementations, since that can enable unsound downcasting.
157 #[unstable(feature = "error_type_id", issue = "60784")]
162 #[stable(feature = "rust1", since = "1.0.0")]
163 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
164 /// Converts a type of [`Error`] into a box of dyn [`Error`].
169 /// use std::error::Error;
176 /// impl fmt::Display for AnError {
177 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 /// write!(f , "An error")
182 /// impl Error for AnError {}
184 /// let an_error = AnError;
185 /// assert!(0 == mem::size_of_val(&an_error));
186 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
187 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
189 fn from(err: E) -> Box<dyn Error + 'a> {
194 #[stable(feature = "rust1", since = "1.0.0")]
195 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
196 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
197 /// dyn [`Error`] + [`Send`] + [`Sync`].
202 /// use std::error::Error;
209 /// impl fmt::Display for AnError {
210 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 /// write!(f , "An error")
215 /// impl Error for AnError {}
217 /// unsafe impl Send for AnError {}
219 /// unsafe impl Sync for AnError {}
221 /// let an_error = AnError;
222 /// assert!(0 == mem::size_of_val(&an_error));
223 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
225 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
227 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl From<String> for Box<dyn Error + Send + Sync> {
234 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
239 /// use std::error::Error;
242 /// let a_string_error = "a string error".to_string();
243 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
245 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
248 fn from(err: String) -> Box<dyn Error + Send + Sync> {
249 struct StringError(String);
251 impl Error for StringError {
253 fn description(&self) -> &str {
258 impl Display for StringError {
259 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260 Display::fmt(&self.0, f)
264 // Purposefully skip printing "StringError(..)"
265 impl Debug for StringError {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 Debug::fmt(&self.0, f)
271 Box::new(StringError(err))
275 #[stable(feature = "string_box_error", since = "1.6.0")]
276 impl From<String> for Box<dyn Error> {
277 /// Converts a [`String`] into a box of dyn [`Error`].
282 /// use std::error::Error;
285 /// let a_string_error = "a string error".to_string();
286 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
287 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
289 fn from(str_err: String) -> Box<dyn Error> {
290 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
291 let err2: Box<dyn Error> = err1;
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
298 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
300 /// [`str`]: prim@str
305 /// use std::error::Error;
308 /// let a_str_error = "a str error";
309 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
311 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
314 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
315 From::from(String::from(err))
319 #[stable(feature = "string_box_error", since = "1.6.0")]
320 impl From<&str> for Box<dyn Error> {
321 /// Converts a [`str`] into a box of dyn [`Error`].
323 /// [`str`]: prim@str
328 /// use std::error::Error;
331 /// let a_str_error = "a str error";
332 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
333 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
335 fn from(err: &str) -> Box<dyn Error> {
336 From::from(String::from(err))
340 #[stable(feature = "cow_box_error", since = "1.22.0")]
341 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
342 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
347 /// use std::error::Error;
349 /// use std::borrow::Cow;
351 /// let a_cow_str_error = Cow::from("a str error");
352 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
354 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
356 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
357 From::from(String::from(err))
361 #[stable(feature = "cow_box_error", since = "1.22.0")]
362 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
363 /// Converts a [`Cow`] into a box of dyn [`Error`].
368 /// use std::error::Error;
370 /// use std::borrow::Cow;
372 /// let a_cow_str_error = Cow::from("a str error");
373 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
374 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
376 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
377 From::from(String::from(err))
381 #[unstable(feature = "never_type", issue = "35121")]
385 feature = "allocator_api",
386 reason = "the precise API and guarantees it provides may be tweaked.",
389 impl Error for AllocError {}
391 #[stable(feature = "alloc_layout", since = "1.28.0")]
392 impl Error for LayoutError {}
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl Error for str::ParseBoolError {
397 fn description(&self) -> &str {
398 "failed to parse bool"
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl Error for str::Utf8Error {
405 fn description(&self) -> &str {
406 "invalid utf-8: corrupt contents"
410 #[stable(feature = "rust1", since = "1.0.0")]
411 impl Error for num::ParseIntError {
413 fn description(&self) -> &str {
418 #[stable(feature = "try_from", since = "1.34.0")]
419 impl Error for num::TryFromIntError {
421 fn description(&self) -> &str {
426 #[stable(feature = "try_from", since = "1.34.0")]
427 impl Error for array::TryFromSliceError {
429 fn description(&self) -> &str {
434 #[stable(feature = "rust1", since = "1.0.0")]
435 impl Error for num::ParseFloatError {
437 fn description(&self) -> &str {
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl Error for string::FromUtf8Error {
445 fn description(&self) -> &str {
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl Error for string::FromUtf16Error {
453 fn description(&self) -> &str {
458 #[stable(feature = "str_parse_error2", since = "1.8.0")]
459 impl Error for Infallible {
460 fn description(&self) -> &str {
465 #[stable(feature = "decode_utf16", since = "1.9.0")]
466 impl Error for char::DecodeUtf16Error {
468 fn description(&self) -> &str {
469 "unpaired surrogate found"
473 #[unstable(feature = "map_try_insert", issue = "82766")]
474 impl<'a, K: Debug + Ord, V: Debug> Error
475 for crate::collections::btree_map::OccupiedError<'a, K, V>
478 fn description(&self) -> &str {
483 #[unstable(feature = "map_try_insert", issue = "82766")]
484 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
486 fn description(&self) -> &str {
491 #[stable(feature = "box_error", since = "1.8.0")]
492 impl<T: Error> Error for Box<T> {
493 #[allow(deprecated, deprecated_in_future)]
494 fn description(&self) -> &str {
495 Error::description(&**self)
499 fn cause(&self) -> Option<&dyn Error> {
500 Error::cause(&**self)
503 fn source(&self) -> Option<&(dyn Error + 'static)> {
504 Error::source(&**self)
508 #[stable(feature = "error_by_ref", since = "1.51.0")]
509 impl<'a, T: Error + ?Sized> Error for &'a T {
510 #[allow(deprecated, deprecated_in_future)]
511 fn description(&self) -> &str {
512 Error::description(&**self)
516 fn cause(&self) -> Option<&dyn Error> {
517 Error::cause(&**self)
520 fn source(&self) -> Option<&(dyn Error + 'static)> {
521 Error::source(&**self)
524 fn backtrace(&self) -> Option<&Backtrace> {
525 Error::backtrace(&**self)
529 #[stable(feature = "arc_error", since = "1.52.0")]
530 impl<T: Error + ?Sized> Error for Arc<T> {
531 #[allow(deprecated, deprecated_in_future)]
532 fn description(&self) -> &str {
533 Error::description(&**self)
537 fn cause(&self) -> Option<&dyn Error> {
538 Error::cause(&**self)
541 fn source(&self) -> Option<&(dyn Error + 'static)> {
542 Error::source(&**self)
545 fn backtrace(&self) -> Option<&Backtrace> {
546 Error::backtrace(&**self)
550 #[stable(feature = "fmt_error", since = "1.11.0")]
551 impl Error for fmt::Error {
553 fn description(&self) -> &str {
554 "an error occurred when formatting an argument"
558 #[stable(feature = "try_borrow", since = "1.13.0")]
559 impl Error for cell::BorrowError {
561 fn description(&self) -> &str {
562 "already mutably borrowed"
566 #[stable(feature = "try_borrow", since = "1.13.0")]
567 impl Error for cell::BorrowMutError {
569 fn description(&self) -> &str {
574 #[stable(feature = "try_from", since = "1.34.0")]
575 impl Error for char::CharTryFromError {
577 fn description(&self) -> &str {
578 "converted integer out of range for `char`"
582 #[stable(feature = "char_from_str", since = "1.20.0")]
583 impl Error for char::ParseCharError {
585 fn description(&self) -> &str {
590 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
591 impl Error for alloc::collections::TryReserveError {}
593 // Copied from `any.rs`.
594 impl dyn Error + 'static {
595 /// Returns `true` if the boxed type is the same as `T`
596 #[stable(feature = "error_downcast", since = "1.3.0")]
598 pub fn is<T: Error + 'static>(&self) -> bool {
599 // Get `TypeId` of the type this function is instantiated with.
600 let t = TypeId::of::<T>();
602 // Get `TypeId` of the type in the trait object.
603 let boxed = self.type_id(private::Internal);
605 // Compare both `TypeId`s on equality.
609 /// Returns some reference to the boxed value if it is of type `T`, or
610 /// `None` if it isn't.
611 #[stable(feature = "error_downcast", since = "1.3.0")]
613 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
615 unsafe { Some(&*(self as *const dyn Error as *const T)) }
621 /// Returns some mutable reference to the boxed value if it is of type `T`, or
622 /// `None` if it isn't.
623 #[stable(feature = "error_downcast", since = "1.3.0")]
625 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
627 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
634 impl dyn Error + 'static + Send {
635 /// Forwards to the method defined on the type `dyn Error`.
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 `dyn Error`.
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 `dyn Error`.
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)
657 impl dyn Error + 'static + Send + Sync {
658 /// Forwards to the method defined on the type `dyn Error`.
659 #[stable(feature = "error_downcast", since = "1.3.0")]
661 pub fn is<T: Error + 'static>(&self) -> bool {
662 <dyn Error + 'static>::is::<T>(self)
665 /// Forwards to the method defined on the type `dyn Error`.
666 #[stable(feature = "error_downcast", since = "1.3.0")]
668 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
669 <dyn Error + 'static>::downcast_ref::<T>(self)
672 /// Forwards to the method defined on the type `dyn Error`.
673 #[stable(feature = "error_downcast", since = "1.3.0")]
675 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
676 <dyn Error + 'static>::downcast_mut::<T>(self)
682 #[stable(feature = "error_downcast", since = "1.3.0")]
683 /// Attempts to downcast the box to a concrete type.
684 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
687 let raw: *mut dyn Error = Box::into_raw(self);
688 Ok(Box::from_raw(raw as *mut T))
695 /// Returns an iterator starting with the current error and continuing with
696 /// recursively calling [`Error::source`].
698 /// If you want to omit the current error and only use its sources,
704 /// #![feature(error_iter)]
705 /// use std::error::Error;
712 /// struct B(Option<Box<dyn Error + 'static>>);
714 /// impl fmt::Display for A {
715 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
720 /// impl fmt::Display for B {
721 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726 /// impl Error for A {}
728 /// impl Error for B {
729 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
730 /// self.0.as_ref().map(|e| e.as_ref())
734 /// let b = B(Some(Box::new(A)));
736 /// // let err : Box<Error> = b.into(); // or
737 /// let err = &b as &(dyn Error);
739 /// let mut iter = err.chain();
741 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
742 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
743 /// assert!(iter.next().is_none());
744 /// assert!(iter.next().is_none());
746 #[unstable(feature = "error_iter", issue = "58520")]
748 pub fn chain(&self) -> Chain<'_> {
749 Chain { current: Some(self) }
753 /// An iterator over an [`Error`] and its sources.
755 /// If you want to omit the initial error and only process
756 /// its sources, use `skip(1)`.
757 #[unstable(feature = "error_iter", issue = "58520")]
758 #[derive(Clone, Debug)]
759 pub struct Chain<'a> {
760 current: Option<&'a (dyn Error + 'static)>,
763 #[unstable(feature = "error_iter", issue = "58520")]
764 impl<'a> Iterator for Chain<'a> {
765 type Item = &'a (dyn Error + 'static);
767 fn next(&mut self) -> Option<Self::Item> {
768 let current = self.current;
769 self.current = self.current.and_then(Error::source);
774 impl dyn Error + Send {
776 #[stable(feature = "error_downcast", since = "1.3.0")]
777 /// Attempts to downcast the box to a concrete type.
778 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
779 let err: Box<dyn Error> = self;
780 <dyn Error>::downcast(err).map_err(|s| unsafe {
781 // Reapply the `Send` marker.
782 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
787 impl dyn Error + Send + Sync {
789 #[stable(feature = "error_downcast", since = "1.3.0")]
790 /// Attempts to downcast the box to a concrete type.
791 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
792 let err: Box<dyn Error> = self;
793 <dyn Error>::downcast(err).map_err(|s| unsafe {
794 // Reapply the `Send + Sync` marker.
795 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)