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;
36 /// `Error` is a trait representing the basic expectations for error values,
37 /// i.e., values of type `E` in [`Result<T, E>`].
39 /// Errors must describe themselves through the [`Display`] and [`Debug`]
40 /// traits. Error messages are typically concise lowercase sentences without
41 /// trailing punctuation:
44 /// let err = "NaN".parse::<u32>().unwrap_err();
45 /// assert_eq!(err.to_string(), "invalid digit found in string");
48 /// Errors may provide cause chain information. [`Error::source()`] is generally
49 /// used when errors cross "abstraction boundaries". If one module must report
50 /// an error that is caused by an error from a lower-level module, it can allow
51 /// accessing that error via [`Error::source()`]. This makes it possible for the
52 /// high-level module to provide its own errors while also revealing some of the
53 /// implementation for debugging via `source` chains.
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub trait Error: Debug + Display {
56 /// The lower-level source of this error, if any.
61 /// use std::error::Error;
65 /// struct SuperError {
66 /// side: SuperErrorSideKick,
69 /// impl fmt::Display for SuperError {
70 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 /// write!(f, "SuperError is here!")
75 /// impl Error for SuperError {
76 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
82 /// struct SuperErrorSideKick;
84 /// impl fmt::Display for SuperErrorSideKick {
85 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 /// write!(f, "SuperErrorSideKick is here!")
90 /// impl Error for SuperErrorSideKick {}
92 /// fn get_super_error() -> Result<(), SuperError> {
93 /// Err(SuperError { side: SuperErrorSideKick })
97 /// match get_super_error() {
99 /// println!("Error: {}", e);
100 /// println!("Caused by: {}", e.source().unwrap());
102 /// _ => println!("No error"),
106 #[stable(feature = "error_source", since = "1.30.0")]
107 fn source(&self) -> Option<&(dyn Error + 'static)> {
111 /// Gets the `TypeId` of `self`.
114 feature = "error_type_id",
115 reason = "this is memory-unsafe to override in user code",
118 fn type_id(&self, _: private::Internal) -> TypeId
125 /// Returns a stack backtrace, if available, of where this error occurred.
127 /// This function allows inspecting the location, in code, of where an error
128 /// happened. The returned `Backtrace` contains information about the stack
129 /// trace of the OS thread of execution of where the error originated from.
131 /// Note that not all errors contain a `Backtrace`. Also note that a
132 /// `Backtrace` may actually be empty. For more information consult the
133 /// `Backtrace` type itself.
134 #[unstable(feature = "backtrace", issue = "53487")]
135 fn backtrace(&self) -> Option<&Backtrace> {
140 /// if let Err(e) = "xc".parse::<u32>() {
141 /// // Print `e` itself, no need for description().
142 /// eprintln!("Error: {}", e);
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
147 fn description(&self) -> &str {
148 "description() is deprecated; use Display"
151 #[stable(feature = "rust1", since = "1.0.0")]
154 reason = "replaced by Error::source, which can support downcasting"
156 #[allow(missing_docs)]
157 fn cause(&self) -> Option<&dyn Error> {
163 // This is a hack to prevent `type_id` from being overridden by `Error`
164 // implementations, since that can enable unsound downcasting.
165 #[unstable(feature = "error_type_id", issue = "60784")]
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
172 /// Converts a type of [`Error`] into a box of dyn [`Error`].
177 /// use std::error::Error;
184 /// impl fmt::Display for AnError {
185 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 /// write!(f, "An error")
190 /// impl Error for AnError {}
192 /// let an_error = AnError;
193 /// assert!(0 == mem::size_of_val(&an_error));
194 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
195 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
197 fn from(err: E) -> Box<dyn Error + 'a> {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
204 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
205 /// dyn [`Error`] + [`Send`] + [`Sync`].
210 /// use std::error::Error;
217 /// impl fmt::Display for AnError {
218 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 /// write!(f, "An error")
223 /// impl Error for AnError {}
225 /// unsafe impl Send for AnError {}
227 /// unsafe impl Sync for AnError {}
229 /// let an_error = AnError;
230 /// assert!(0 == mem::size_of_val(&an_error));
231 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
233 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
235 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
240 #[stable(feature = "rust1", since = "1.0.0")]
241 impl From<String> for Box<dyn Error + Send + Sync> {
242 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
247 /// use std::error::Error;
250 /// let a_string_error = "a string error".to_string();
251 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
253 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
256 fn from(err: String) -> Box<dyn Error + Send + Sync> {
257 struct StringError(String);
259 impl Error for StringError {
261 fn description(&self) -> &str {
266 impl Display for StringError {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 Display::fmt(&self.0, f)
272 // Purposefully skip printing "StringError(..)"
273 impl Debug for StringError {
274 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
275 Debug::fmt(&self.0, f)
279 Box::new(StringError(err))
283 #[stable(feature = "string_box_error", since = "1.6.0")]
284 impl From<String> for Box<dyn Error> {
285 /// Converts a [`String`] into a box of dyn [`Error`].
290 /// use std::error::Error;
293 /// let a_string_error = "a string error".to_string();
294 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
295 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
297 fn from(str_err: String) -> Box<dyn Error> {
298 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
299 let err2: Box<dyn Error> = err1;
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
306 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
308 /// [`str`]: prim@str
313 /// use std::error::Error;
316 /// let a_str_error = "a str error";
317 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
319 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
322 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
323 From::from(String::from(err))
327 #[stable(feature = "string_box_error", since = "1.6.0")]
328 impl From<&str> for Box<dyn Error> {
329 /// Converts a [`str`] into a box of dyn [`Error`].
331 /// [`str`]: prim@str
336 /// use std::error::Error;
339 /// let a_str_error = "a str error";
340 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
341 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
343 fn from(err: &str) -> Box<dyn Error> {
344 From::from(String::from(err))
348 #[stable(feature = "cow_box_error", since = "1.22.0")]
349 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
350 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
355 /// use std::error::Error;
357 /// use std::borrow::Cow;
359 /// let a_cow_str_error = Cow::from("a str error");
360 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
362 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
364 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
365 From::from(String::from(err))
369 #[stable(feature = "cow_box_error", since = "1.22.0")]
370 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
371 /// Converts a [`Cow`] into a box of dyn [`Error`].
376 /// use std::error::Error;
378 /// use std::borrow::Cow;
380 /// let a_cow_str_error = Cow::from("a str error");
381 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
382 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
384 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
385 From::from(String::from(err))
389 #[unstable(feature = "never_type", issue = "35121")]
393 feature = "allocator_api",
394 reason = "the precise API and guarantees it provides may be tweaked.",
397 impl Error for AllocError {}
399 #[stable(feature = "alloc_layout", since = "1.28.0")]
400 impl Error for LayoutError {}
402 #[stable(feature = "rust1", since = "1.0.0")]
403 impl Error for str::ParseBoolError {
405 fn description(&self) -> &str {
406 "failed to parse bool"
410 #[stable(feature = "rust1", since = "1.0.0")]
411 impl Error for str::Utf8Error {
413 fn description(&self) -> &str {
414 "invalid utf-8: corrupt contents"
418 #[stable(feature = "rust1", since = "1.0.0")]
419 impl Error for num::ParseIntError {
421 fn description(&self) -> &str {
426 #[stable(feature = "try_from", since = "1.34.0")]
427 impl Error for num::TryFromIntError {
429 fn description(&self) -> &str {
434 #[stable(feature = "try_from", since = "1.34.0")]
435 impl Error for array::TryFromSliceError {
437 fn description(&self) -> &str {
442 #[stable(feature = "rust1", since = "1.0.0")]
443 impl Error for num::ParseFloatError {
445 fn description(&self) -> &str {
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl Error for string::FromUtf8Error {
453 fn description(&self) -> &str {
458 #[stable(feature = "rust1", since = "1.0.0")]
459 impl Error for string::FromUtf16Error {
461 fn description(&self) -> &str {
466 #[stable(feature = "str_parse_error2", since = "1.8.0")]
467 impl Error for Infallible {
468 fn description(&self) -> &str {
473 #[stable(feature = "decode_utf16", since = "1.9.0")]
474 impl Error for char::DecodeUtf16Error {
476 fn description(&self) -> &str {
477 "unpaired surrogate found"
481 #[unstable(feature = "map_try_insert", issue = "82766")]
482 impl<'a, K: Debug + Ord, V: Debug> Error
483 for crate::collections::btree_map::OccupiedError<'a, K, V>
486 fn description(&self) -> &str {
491 #[unstable(feature = "map_try_insert", issue = "82766")]
492 impl<'a, K: Debug, V: Debug> Error for crate::collections::hash_map::OccupiedError<'a, K, V> {
494 fn description(&self) -> &str {
499 #[stable(feature = "box_error", since = "1.8.0")]
500 impl<T: Error> Error for Box<T> {
501 #[allow(deprecated, deprecated_in_future)]
502 fn description(&self) -> &str {
503 Error::description(&**self)
507 fn cause(&self) -> Option<&dyn Error> {
508 Error::cause(&**self)
511 fn source(&self) -> Option<&(dyn Error + 'static)> {
512 Error::source(&**self)
516 #[stable(feature = "error_by_ref", since = "1.51.0")]
517 impl<'a, T: Error + ?Sized> Error for &'a T {
518 #[allow(deprecated, deprecated_in_future)]
519 fn description(&self) -> &str {
520 Error::description(&**self)
524 fn cause(&self) -> Option<&dyn Error> {
525 Error::cause(&**self)
528 fn source(&self) -> Option<&(dyn Error + 'static)> {
529 Error::source(&**self)
532 fn backtrace(&self) -> Option<&Backtrace> {
533 Error::backtrace(&**self)
537 #[stable(feature = "arc_error", since = "1.52.0")]
538 impl<T: Error + ?Sized> Error for Arc<T> {
539 #[allow(deprecated, deprecated_in_future)]
540 fn description(&self) -> &str {
541 Error::description(&**self)
545 fn cause(&self) -> Option<&dyn Error> {
546 Error::cause(&**self)
549 fn source(&self) -> Option<&(dyn Error + 'static)> {
550 Error::source(&**self)
553 fn backtrace(&self) -> Option<&Backtrace> {
554 Error::backtrace(&**self)
558 #[stable(feature = "fmt_error", since = "1.11.0")]
559 impl Error for fmt::Error {
561 fn description(&self) -> &str {
562 "an error occurred when formatting an argument"
566 #[stable(feature = "try_borrow", since = "1.13.0")]
567 impl Error for cell::BorrowError {
569 fn description(&self) -> &str {
570 "already mutably borrowed"
574 #[stable(feature = "try_borrow", since = "1.13.0")]
575 impl Error for cell::BorrowMutError {
577 fn description(&self) -> &str {
582 #[stable(feature = "try_from", since = "1.34.0")]
583 impl Error for char::CharTryFromError {
585 fn description(&self) -> &str {
586 "converted integer out of range for `char`"
590 #[stable(feature = "char_from_str", since = "1.20.0")]
591 impl Error for char::ParseCharError {
593 fn description(&self) -> &str {
598 #[stable(feature = "try_reserve", since = "1.57.0")]
599 impl Error for alloc::collections::TryReserveError {}
601 #[unstable(feature = "duration_checked_float", issue = "83400")]
602 impl Error for time::FromSecsError {}
604 // Copied from `any.rs`.
605 impl dyn Error + 'static {
606 /// Returns `true` if the boxed type is the same as `T`
607 #[stable(feature = "error_downcast", since = "1.3.0")]
609 pub fn is<T: Error + 'static>(&self) -> bool {
610 // Get `TypeId` of the type this function is instantiated with.
611 let t = TypeId::of::<T>();
613 // Get `TypeId` of the type in the trait object.
614 let boxed = self.type_id(private::Internal);
616 // Compare both `TypeId`s on equality.
620 /// Returns some reference to the boxed value if it is of type `T`, or
621 /// `None` if it isn't.
622 #[stable(feature = "error_downcast", since = "1.3.0")]
624 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
626 unsafe { Some(&*(self as *const dyn Error as *const T)) }
632 /// Returns some mutable reference to the boxed value if it is of type `T`, or
633 /// `None` if it isn't.
634 #[stable(feature = "error_downcast", since = "1.3.0")]
636 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
638 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
645 impl dyn Error + 'static + Send {
646 /// Forwards to the method defined on the type `dyn Error`.
647 #[stable(feature = "error_downcast", since = "1.3.0")]
649 pub fn is<T: Error + 'static>(&self) -> bool {
650 <dyn Error + 'static>::is::<T>(self)
653 /// Forwards to the method defined on the type `dyn Error`.
654 #[stable(feature = "error_downcast", since = "1.3.0")]
656 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
657 <dyn Error + 'static>::downcast_ref::<T>(self)
660 /// Forwards to the method defined on the type `dyn Error`.
661 #[stable(feature = "error_downcast", since = "1.3.0")]
663 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
664 <dyn Error + 'static>::downcast_mut::<T>(self)
668 impl dyn Error + 'static + Send + Sync {
669 /// Forwards to the method defined on the type `dyn Error`.
670 #[stable(feature = "error_downcast", since = "1.3.0")]
672 pub fn is<T: Error + 'static>(&self) -> bool {
673 <dyn Error + 'static>::is::<T>(self)
676 /// Forwards to the method defined on the type `dyn Error`.
677 #[stable(feature = "error_downcast", since = "1.3.0")]
679 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
680 <dyn Error + 'static>::downcast_ref::<T>(self)
683 /// Forwards to the method defined on the type `dyn Error`.
684 #[stable(feature = "error_downcast", since = "1.3.0")]
686 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
687 <dyn Error + 'static>::downcast_mut::<T>(self)
693 #[stable(feature = "error_downcast", since = "1.3.0")]
694 /// Attempts to downcast the box to a concrete type.
695 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
698 let raw: *mut dyn Error = Box::into_raw(self);
699 Ok(Box::from_raw(raw as *mut T))
706 /// Returns an iterator starting with the current error and continuing with
707 /// recursively calling [`Error::source`].
709 /// If you want to omit the current error and only use its sources,
715 /// #![feature(error_iter)]
716 /// use std::error::Error;
723 /// struct B(Option<Box<dyn Error + 'static>>);
725 /// impl fmt::Display for A {
726 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
731 /// impl fmt::Display for B {
732 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737 /// impl Error for A {}
739 /// impl Error for B {
740 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
741 /// self.0.as_ref().map(|e| e.as_ref())
745 /// let b = B(Some(Box::new(A)));
747 /// // let err : Box<Error> = b.into(); // or
748 /// let err = &b as &(dyn Error);
750 /// let mut iter = err.chain();
752 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
753 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
754 /// assert!(iter.next().is_none());
755 /// assert!(iter.next().is_none());
757 #[unstable(feature = "error_iter", issue = "58520")]
759 pub fn chain(&self) -> Chain<'_> {
760 Chain { current: Some(self) }
764 /// An iterator over an [`Error`] and its sources.
766 /// If you want to omit the initial error and only process
767 /// its sources, use `skip(1)`.
768 #[unstable(feature = "error_iter", issue = "58520")]
769 #[derive(Clone, Debug)]
770 pub struct Chain<'a> {
771 current: Option<&'a (dyn Error + 'static)>,
774 #[unstable(feature = "error_iter", issue = "58520")]
775 impl<'a> Iterator for Chain<'a> {
776 type Item = &'a (dyn Error + 'static);
778 fn next(&mut self) -> Option<Self::Item> {
779 let current = self.current;
780 self.current = self.current.and_then(Error::source);
785 impl dyn Error + Send {
787 #[stable(feature = "error_downcast", since = "1.3.0")]
788 /// Attempts to downcast the box to a concrete type.
789 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
790 let err: Box<dyn Error> = self;
791 <dyn Error>::downcast(err).map_err(|s| unsafe {
792 // Reapply the `Send` marker.
793 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
798 impl dyn Error + Send + Sync {
800 #[stable(feature = "error_downcast", since = "1.3.0")]
801 /// Attempts to downcast the box to a concrete type.
802 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
803 let err: Box<dyn Error> = self;
804 <dyn Error>::downcast(err).map_err(|s| unsafe {
805 // Reapply the `Send + Sync` marker.
806 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)