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 /// [`Error::source()`] is generally used when errors cross
37 /// "abstraction boundaries". If one module must report an error that is caused
38 /// by an error from a lower-level module, it can allow accessing that error
39 /// via [`Error::source()`]. This makes it possible for the high-level
40 /// module to provide its own errors while also revealing some of the
41 /// implementation for debugging via `source` chains.
43 /// [`Result<T, E>`]: Result
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub trait Error: Debug + Display {
46 /// The lower-level source of this error, if any.
51 /// use std::error::Error;
55 /// struct SuperError {
56 /// side: SuperErrorSideKick,
59 /// impl fmt::Display for SuperError {
60 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 /// write!(f, "SuperError is here!")
65 /// impl Error for SuperError {
66 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
72 /// struct SuperErrorSideKick;
74 /// impl fmt::Display for SuperErrorSideKick {
75 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 /// write!(f, "SuperErrorSideKick is here!")
80 /// impl Error for SuperErrorSideKick {}
82 /// fn get_super_error() -> Result<(), SuperError> {
83 /// Err(SuperError { side: SuperErrorSideKick })
87 /// match get_super_error() {
89 /// println!("Error: {}", e);
90 /// println!("Caused by: {}", e.source().unwrap());
92 /// _ => println!("No error"),
96 #[stable(feature = "error_source", since = "1.30.0")]
97 fn source(&self) -> Option<&(dyn Error + 'static)> {
101 /// Gets the `TypeId` of `self`.
104 feature = "error_type_id",
105 reason = "this is memory-unsafe to override in user code",
108 fn type_id(&self, _: private::Internal) -> TypeId
115 /// Returns a stack backtrace, if available, of where this error occurred.
117 /// This function allows inspecting the location, in code, of where an error
118 /// happened. The returned `Backtrace` contains information about the stack
119 /// trace of the OS thread of execution of where the error originated from.
121 /// Note that not all errors contain a `Backtrace`. Also note that a
122 /// `Backtrace` may actually be empty. For more information consult the
123 /// `Backtrace` type itself.
124 #[unstable(feature = "backtrace", issue = "53487")]
125 fn backtrace(&self) -> Option<&Backtrace> {
130 /// if let Err(e) = "xc".parse::<u32>() {
131 /// // Print `e` itself, no need for description().
132 /// eprintln!("Error: {}", e);
135 #[stable(feature = "rust1", since = "1.0.0")]
136 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
137 fn description(&self) -> &str {
138 "description() is deprecated; use Display"
141 #[stable(feature = "rust1", since = "1.0.0")]
144 reason = "replaced by Error::source, which can support downcasting"
146 #[allow(missing_docs)]
147 fn cause(&self) -> Option<&dyn Error> {
153 // This is a hack to prevent `type_id` from being overridden by `Error`
154 // implementations, since that can enable unsound downcasting.
155 #[unstable(feature = "error_type_id", issue = "60784")]
160 #[stable(feature = "rust1", since = "1.0.0")]
161 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
162 /// Converts a type of [`Error`] into a box of dyn [`Error`].
167 /// use std::error::Error;
174 /// impl fmt::Display for AnError {
175 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 /// write!(f , "An error")
180 /// impl Error for AnError {}
182 /// let an_error = AnError;
183 /// assert!(0 == mem::size_of_val(&an_error));
184 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
185 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
187 fn from(err: E) -> Box<dyn Error + 'a> {
192 #[stable(feature = "rust1", since = "1.0.0")]
193 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
194 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
195 /// dyn [`Error`] + [`Send`] + [`Sync`].
200 /// use std::error::Error;
207 /// impl fmt::Display for AnError {
208 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
209 /// write!(f , "An error")
213 /// impl Error for AnError {}
215 /// unsafe impl Send for AnError {}
217 /// unsafe impl Sync for AnError {}
219 /// let an_error = AnError;
220 /// assert!(0 == mem::size_of_val(&an_error));
221 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
223 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
225 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl From<String> for Box<dyn Error + Send + Sync> {
232 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
237 /// use std::error::Error;
240 /// let a_string_error = "a string error".to_string();
241 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
243 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
246 fn from(err: String) -> Box<dyn Error + Send + Sync> {
247 struct StringError(String);
249 impl Error for StringError {
251 fn description(&self) -> &str {
256 impl Display for StringError {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 Display::fmt(&self.0, f)
262 // Purposefully skip printing "StringError(..)"
263 impl Debug for StringError {
264 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265 Debug::fmt(&self.0, f)
269 Box::new(StringError(err))
273 #[stable(feature = "string_box_error", since = "1.6.0")]
274 impl From<String> for Box<dyn Error> {
275 /// Converts a [`String`] into a box of dyn [`Error`].
280 /// use std::error::Error;
283 /// let a_string_error = "a string error".to_string();
284 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
285 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
287 fn from(str_err: String) -> Box<dyn Error> {
288 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
289 let err2: Box<dyn Error> = err1;
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
296 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
298 /// [`str`]: prim@str
303 /// use std::error::Error;
306 /// let a_str_error = "a str error";
307 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
309 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
312 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
313 From::from(String::from(err))
317 #[stable(feature = "string_box_error", since = "1.6.0")]
318 impl From<&str> for Box<dyn Error> {
319 /// Converts a [`str`] into a box of dyn [`Error`].
321 /// [`str`]: prim@str
326 /// use std::error::Error;
329 /// let a_str_error = "a str error";
330 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
331 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
333 fn from(err: &str) -> Box<dyn Error> {
334 From::from(String::from(err))
338 #[stable(feature = "cow_box_error", since = "1.22.0")]
339 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
340 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
345 /// use std::error::Error;
347 /// use std::borrow::Cow;
349 /// let a_cow_str_error = Cow::from("a str error");
350 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
352 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
354 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
355 From::from(String::from(err))
359 #[stable(feature = "cow_box_error", since = "1.22.0")]
360 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
361 /// Converts a [`Cow`] into a box of dyn [`Error`].
366 /// use std::error::Error;
368 /// use std::borrow::Cow;
370 /// let a_cow_str_error = Cow::from("a str error");
371 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
372 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
374 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
375 From::from(String::from(err))
379 #[unstable(feature = "never_type", issue = "35121")]
383 feature = "allocator_api",
384 reason = "the precise API and guarantees it provides may be tweaked.",
387 impl Error for AllocErr {}
390 feature = "allocator_api",
391 reason = "the precise API and guarantees it provides may be tweaked.",
394 impl Error for LayoutErr {}
396 #[stable(feature = "rust1", since = "1.0.0")]
397 impl Error for str::ParseBoolError {
399 fn description(&self) -> &str {
400 "failed to parse bool"
404 #[stable(feature = "rust1", since = "1.0.0")]
405 impl Error for str::Utf8Error {
407 fn description(&self) -> &str {
408 "invalid utf-8: corrupt contents"
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl Error for num::ParseIntError {
415 fn description(&self) -> &str {
420 #[stable(feature = "try_from", since = "1.34.0")]
421 impl Error for num::TryFromIntError {
423 fn description(&self) -> &str {
428 #[stable(feature = "try_from", since = "1.34.0")]
429 impl Error for array::TryFromSliceError {
431 fn description(&self) -> &str {
436 #[stable(feature = "rust1", since = "1.0.0")]
437 impl Error for num::ParseFloatError {
439 fn description(&self) -> &str {
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl Error for string::FromUtf8Error {
447 fn description(&self) -> &str {
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl Error for string::FromUtf16Error {
455 fn description(&self) -> &str {
460 #[stable(feature = "str_parse_error2", since = "1.8.0")]
461 impl Error for Infallible {
462 fn description(&self) -> &str {
467 #[stable(feature = "decode_utf16", since = "1.9.0")]
468 impl Error for char::DecodeUtf16Error {
470 fn description(&self) -> &str {
471 "unpaired surrogate found"
475 #[stable(feature = "box_error", since = "1.8.0")]
476 impl<T: Error> Error for Box<T> {
477 #[allow(deprecated, deprecated_in_future)]
478 fn description(&self) -> &str {
479 Error::description(&**self)
483 fn cause(&self) -> Option<&dyn Error> {
484 Error::cause(&**self)
487 fn source(&self) -> Option<&(dyn Error + 'static)> {
488 Error::source(&**self)
492 #[stable(feature = "fmt_error", since = "1.11.0")]
493 impl Error for fmt::Error {
495 fn description(&self) -> &str {
496 "an error occurred when formatting an argument"
500 #[stable(feature = "try_borrow", since = "1.13.0")]
501 impl Error for cell::BorrowError {
503 fn description(&self) -> &str {
504 "already mutably borrowed"
508 #[stable(feature = "try_borrow", since = "1.13.0")]
509 impl Error for cell::BorrowMutError {
511 fn description(&self) -> &str {
516 #[stable(feature = "try_from", since = "1.34.0")]
517 impl Error for char::CharTryFromError {
519 fn description(&self) -> &str {
520 "converted integer out of range for `char`"
524 #[stable(feature = "char_from_str", since = "1.20.0")]
525 impl Error for char::ParseCharError {
527 fn description(&self) -> &str {
532 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
533 impl Error for alloc::collections::TryReserveError {}
535 // Copied from `any.rs`.
536 impl dyn Error + 'static {
537 /// Returns `true` if the boxed type is the same as `T`
538 #[stable(feature = "error_downcast", since = "1.3.0")]
540 pub fn is<T: Error + 'static>(&self) -> bool {
541 // Get `TypeId` of the type this function is instantiated with.
542 let t = TypeId::of::<T>();
544 // Get `TypeId` of the type in the trait object.
545 let boxed = self.type_id(private::Internal);
547 // Compare both `TypeId`s on equality.
551 /// Returns some reference to the boxed value if it is of type `T`, or
552 /// `None` if it isn't.
553 #[stable(feature = "error_downcast", since = "1.3.0")]
555 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
557 unsafe { Some(&*(self as *const dyn Error as *const T)) }
563 /// Returns some mutable reference to the boxed value if it is of type `T`, or
564 /// `None` if it isn't.
565 #[stable(feature = "error_downcast", since = "1.3.0")]
567 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
569 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
576 impl dyn Error + 'static + Send {
577 /// Forwards to the method defined on the type `dyn Error`.
578 #[stable(feature = "error_downcast", since = "1.3.0")]
580 pub fn is<T: Error + 'static>(&self) -> bool {
581 <dyn Error + 'static>::is::<T>(self)
584 /// Forwards to the method defined on the type `dyn Error`.
585 #[stable(feature = "error_downcast", since = "1.3.0")]
587 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
588 <dyn Error + 'static>::downcast_ref::<T>(self)
591 /// Forwards to the method defined on the type `dyn Error`.
592 #[stable(feature = "error_downcast", since = "1.3.0")]
594 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
595 <dyn Error + 'static>::downcast_mut::<T>(self)
599 impl dyn Error + 'static + Send + Sync {
600 /// Forwards to the method defined on the type `dyn Error`.
601 #[stable(feature = "error_downcast", since = "1.3.0")]
603 pub fn is<T: Error + 'static>(&self) -> bool {
604 <dyn Error + 'static>::is::<T>(self)
607 /// Forwards to the method defined on the type `dyn Error`.
608 #[stable(feature = "error_downcast", since = "1.3.0")]
610 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
611 <dyn Error + 'static>::downcast_ref::<T>(self)
614 /// Forwards to the method defined on the type `dyn Error`.
615 #[stable(feature = "error_downcast", since = "1.3.0")]
617 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
618 <dyn Error + 'static>::downcast_mut::<T>(self)
624 #[stable(feature = "error_downcast", since = "1.3.0")]
625 /// Attempts to downcast the box to a concrete type.
626 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
629 let raw: *mut dyn Error = Box::into_raw(self);
630 Ok(Box::from_raw(raw as *mut T))
637 /// Returns an iterator starting with the current error and continuing with
638 /// recursively calling [`Error::source`].
640 /// If you want to omit the current error and only use its sources,
646 /// #![feature(error_iter)]
647 /// use std::error::Error;
654 /// struct B(Option<Box<dyn Error + 'static>>);
656 /// impl fmt::Display for A {
657 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662 /// impl fmt::Display for B {
663 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
668 /// impl Error for A {}
670 /// impl Error for B {
671 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
672 /// self.0.as_ref().map(|e| e.as_ref())
676 /// let b = B(Some(Box::new(A)));
678 /// // let err : Box<Error> = b.into(); // or
679 /// let err = &b as &(dyn Error);
681 /// let mut iter = err.chain();
683 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
684 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
685 /// assert!(iter.next().is_none());
686 /// assert!(iter.next().is_none());
688 #[unstable(feature = "error_iter", issue = "58520")]
690 pub fn chain(&self) -> Chain<'_> {
691 Chain { current: Some(self) }
695 /// An iterator over an [`Error`] and its sources.
697 /// If you want to omit the initial error and only process
698 /// its sources, use `skip(1)`.
699 #[unstable(feature = "error_iter", issue = "58520")]
700 #[derive(Clone, Debug)]
701 pub struct Chain<'a> {
702 current: Option<&'a (dyn Error + 'static)>,
705 #[unstable(feature = "error_iter", issue = "58520")]
706 impl<'a> Iterator for Chain<'a> {
707 type Item = &'a (dyn Error + 'static);
709 fn next(&mut self) -> Option<Self::Item> {
710 let current = self.current;
711 self.current = self.current.and_then(Error::source);
716 impl dyn Error + Send {
718 #[stable(feature = "error_downcast", since = "1.3.0")]
719 /// Attempts to downcast the box to a concrete type.
720 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
721 let err: Box<dyn Error> = self;
722 <dyn Error>::downcast(err).map_err(|s| unsafe {
723 // Reapply the `Send` marker.
724 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
729 impl dyn Error + Send + Sync {
731 #[stable(feature = "error_downcast", since = "1.3.0")]
732 /// Attempts to downcast the box to a concrete type.
733 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
734 let err: Box<dyn Error> = self;
735 <dyn Error>::downcast(err).map_err(|s| unsafe {
736 // Reapply the `Send + Sync` marker.
737 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
747 #[derive(Debug, PartialEq)]
749 #[derive(Debug, PartialEq)]
752 impl fmt::Display for A {
753 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
757 impl fmt::Display for B {
758 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 let a = &mut a as &mut (dyn Error + 'static);
770 assert_eq!(a.downcast_ref::<A>(), Some(&A));
771 assert_eq!(a.downcast_ref::<B>(), None);
772 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
773 assert_eq!(a.downcast_mut::<B>(), None);
775 let a: Box<dyn Error> = Box::new(A);
776 match a.downcast::<B>() {
777 Ok(..) => panic!("expected error"),
778 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),