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 /// 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.description());
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.41.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`].
166 /// [`Error`]: ../error/trait.Error.html
171 /// use std::error::Error;
178 /// impl fmt::Display for AnError {
179 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 /// write!(f , "An error")
184 /// impl Error for AnError {}
186 /// let an_error = AnError;
187 /// assert!(0 == mem::size_of_val(&an_error));
188 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
189 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
191 fn from(err: E) -> Box<dyn Error + 'a> {
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
198 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
199 /// dyn [`Error`] + [`Send`] + [`Sync`].
201 /// [`Error`]: ../error/trait.Error.html
206 /// use std::error::Error;
213 /// impl fmt::Display for AnError {
214 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 /// write!(f , "An error")
219 /// impl Error for AnError {}
221 /// unsafe impl Send for AnError {}
223 /// unsafe impl Sync for AnError {}
225 /// let an_error = AnError;
226 /// assert!(0 == mem::size_of_val(&an_error));
227 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
229 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
231 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
236 #[stable(feature = "rust1", since = "1.0.0")]
237 impl From<String> for Box<dyn Error + Send + Sync> {
238 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
240 /// [`Error`]: ../error/trait.Error.html
245 /// use std::error::Error;
248 /// let a_string_error = "a string error".to_string();
249 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
251 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
254 fn from(err: String) -> Box<dyn Error + Send + Sync> {
255 struct StringError(String);
257 impl Error for StringError {
259 fn description(&self) -> &str {
264 impl Display for StringError {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 Display::fmt(&self.0, f)
270 // Purposefully skip printing "StringError(..)"
271 impl Debug for StringError {
272 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273 Debug::fmt(&self.0, f)
277 Box::new(StringError(err))
281 #[stable(feature = "string_box_error", since = "1.6.0")]
282 impl From<String> for Box<dyn Error> {
283 /// Converts a [`String`] into a box of dyn [`Error`].
285 /// [`Error`]: ../error/trait.Error.html
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 /// [`Error`]: ../error/trait.Error.html
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 /// [`Error`]: ../error/trait.Error.html
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`].
352 /// [`Cow`]: ../borrow/enum.Cow.html
353 /// [`Error`]: ../error/trait.Error.html
358 /// use std::error::Error;
360 /// use std::borrow::Cow;
362 /// let a_cow_str_error = Cow::from("a str error");
363 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
365 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
367 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
368 From::from(String::from(err))
372 #[stable(feature = "cow_box_error", since = "1.22.0")]
373 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
374 /// Converts a [`Cow`] into a box of dyn [`Error`].
376 /// [`Cow`]: ../borrow/enum.Cow.html
377 /// [`Error`]: ../error/trait.Error.html
382 /// use std::error::Error;
384 /// use std::borrow::Cow;
386 /// let a_cow_str_error = Cow::from("a str error");
387 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
388 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
390 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
391 From::from(String::from(err))
395 #[unstable(feature = "never_type", issue = "35121")]
399 feature = "allocator_api",
400 reason = "the precise API and guarantees it provides may be tweaked.",
403 impl Error for AllocErr {}
406 feature = "allocator_api",
407 reason = "the precise API and guarantees it provides may be tweaked.",
410 impl Error for LayoutErr {}
413 feature = "allocator_api",
414 reason = "the precise API and guarantees it provides may be tweaked.",
417 impl Error for CannotReallocInPlace {}
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl Error for str::ParseBoolError {
422 fn description(&self) -> &str {
423 "failed to parse bool"
427 #[stable(feature = "rust1", since = "1.0.0")]
428 impl Error for str::Utf8Error {
430 fn description(&self) -> &str {
431 "invalid utf-8: corrupt contents"
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl Error for num::ParseIntError {
438 fn description(&self) -> &str {
443 #[stable(feature = "try_from", since = "1.34.0")]
444 impl Error for num::TryFromIntError {
446 fn description(&self) -> &str {
451 #[stable(feature = "try_from", since = "1.34.0")]
452 impl Error for array::TryFromSliceError {
454 fn description(&self) -> &str {
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl Error for num::ParseFloatError {
462 fn description(&self) -> &str {
467 #[stable(feature = "rust1", since = "1.0.0")]
468 impl Error for string::FromUtf8Error {
470 fn description(&self) -> &str {
475 #[stable(feature = "rust1", since = "1.0.0")]
476 impl Error for string::FromUtf16Error {
478 fn description(&self) -> &str {
483 #[stable(feature = "str_parse_error2", since = "1.8.0")]
484 impl Error for string::ParseError {
485 fn description(&self) -> &str {
490 #[stable(feature = "decode_utf16", since = "1.9.0")]
491 impl Error for char::DecodeUtf16Error {
493 fn description(&self) -> &str {
494 "unpaired surrogate found"
498 #[stable(feature = "box_error", since = "1.8.0")]
499 impl<T: Error> Error for Box<T> {
500 #[allow(deprecated, deprecated_in_future)]
501 fn description(&self) -> &str {
502 Error::description(&**self)
506 fn cause(&self) -> Option<&dyn Error> {
507 Error::cause(&**self)
510 fn source(&self) -> Option<&(dyn Error + 'static)> {
511 Error::source(&**self)
515 #[stable(feature = "fmt_error", since = "1.11.0")]
516 impl Error for fmt::Error {
518 fn description(&self) -> &str {
519 "an error occurred when formatting an argument"
523 #[stable(feature = "try_borrow", since = "1.13.0")]
524 impl Error for cell::BorrowError {
526 fn description(&self) -> &str {
527 "already mutably borrowed"
531 #[stable(feature = "try_borrow", since = "1.13.0")]
532 impl Error for cell::BorrowMutError {
534 fn description(&self) -> &str {
539 #[stable(feature = "try_from", since = "1.34.0")]
540 impl Error for char::CharTryFromError {
542 fn description(&self) -> &str {
543 "converted integer out of range for `char`"
547 #[stable(feature = "char_from_str", since = "1.20.0")]
548 impl Error for char::ParseCharError {
550 fn description(&self) -> &str {
555 // Copied from `any.rs`.
556 impl dyn Error + 'static {
557 /// Returns `true` if the boxed type is the same as `T`
558 #[stable(feature = "error_downcast", since = "1.3.0")]
560 pub fn is<T: Error + 'static>(&self) -> bool {
561 // Get `TypeId` of the type this function is instantiated with.
562 let t = TypeId::of::<T>();
564 // Get `TypeId` of the type in the trait object.
565 let boxed = self.type_id(private::Internal);
567 // Compare both `TypeId`s on equality.
571 /// Returns some reference to the boxed value if it is of type `T`, or
572 /// `None` if it isn't.
573 #[stable(feature = "error_downcast", since = "1.3.0")]
575 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
577 unsafe { Some(&*(self as *const dyn Error as *const T)) }
583 /// Returns some mutable reference to the boxed value if it is of type `T`, or
584 /// `None` if it isn't.
585 #[stable(feature = "error_downcast", since = "1.3.0")]
587 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
589 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
596 impl dyn Error + 'static + Send {
597 /// Forwards to the method defined on the type `dyn Error`.
598 #[stable(feature = "error_downcast", since = "1.3.0")]
600 pub fn is<T: Error + 'static>(&self) -> bool {
601 <dyn Error + 'static>::is::<T>(self)
604 /// Forwards to the method defined on the type `dyn Error`.
605 #[stable(feature = "error_downcast", since = "1.3.0")]
607 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
608 <dyn Error + 'static>::downcast_ref::<T>(self)
611 /// Forwards to the method defined on the type `dyn Error`.
612 #[stable(feature = "error_downcast", since = "1.3.0")]
614 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
615 <dyn Error + 'static>::downcast_mut::<T>(self)
619 impl dyn Error + 'static + Send + Sync {
620 /// Forwards to the method defined on the type `dyn Error`.
621 #[stable(feature = "error_downcast", since = "1.3.0")]
623 pub fn is<T: Error + 'static>(&self) -> bool {
624 <dyn Error + 'static>::is::<T>(self)
627 /// Forwards to the method defined on the type `dyn Error`.
628 #[stable(feature = "error_downcast", since = "1.3.0")]
630 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
631 <dyn Error + 'static>::downcast_ref::<T>(self)
634 /// Forwards to the method defined on the type `dyn Error`.
635 #[stable(feature = "error_downcast", since = "1.3.0")]
637 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
638 <dyn Error + 'static>::downcast_mut::<T>(self)
644 #[stable(feature = "error_downcast", since = "1.3.0")]
645 /// Attempts to downcast the box to a concrete type.
646 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
649 let raw: *mut dyn Error = Box::into_raw(self);
650 Ok(Box::from_raw(raw as *mut T))
657 /// Returns an iterator starting with the current error and continuing with
658 /// recursively calling [`source`].
660 /// If you want to omit the current error and only use its sources,
666 /// #![feature(error_iter)]
667 /// use std::error::Error;
674 /// struct B(Option<Box<dyn Error + 'static>>);
676 /// impl fmt::Display for A {
677 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682 /// impl fmt::Display for B {
683 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
688 /// impl Error for A {}
690 /// impl Error for B {
691 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
692 /// self.0.as_ref().map(|e| e.as_ref())
696 /// let b = B(Some(Box::new(A)));
698 /// // let err : Box<Error> = b.into(); // or
699 /// let err = &b as &(dyn Error);
701 /// let mut iter = err.chain();
703 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
704 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
705 /// assert!(iter.next().is_none());
706 /// assert!(iter.next().is_none());
709 /// [`source`]: trait.Error.html#method.source
710 #[unstable(feature = "error_iter", issue = "58520")]
712 pub fn chain(&self) -> Chain<'_> {
713 Chain { current: Some(self) }
717 /// An iterator over an [`Error`] and its sources.
719 /// If you want to omit the initial error and only process
720 /// its sources, use `skip(1)`.
722 /// [`Error`]: trait.Error.html
723 #[unstable(feature = "error_iter", issue = "58520")]
724 #[derive(Clone, Debug)]
725 pub struct Chain<'a> {
726 current: Option<&'a (dyn Error + 'static)>,
729 #[unstable(feature = "error_iter", issue = "58520")]
730 impl<'a> Iterator for Chain<'a> {
731 type Item = &'a (dyn Error + 'static);
733 fn next(&mut self) -> Option<Self::Item> {
734 let current = self.current;
735 self.current = self.current.and_then(Error::source);
740 impl dyn Error + Send {
742 #[stable(feature = "error_downcast", since = "1.3.0")]
743 /// Attempts to downcast the box to a concrete type.
744 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
745 let err: Box<dyn Error> = self;
746 <dyn Error>::downcast(err).map_err(|s| unsafe {
747 // Reapply the `Send` marker.
748 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
753 impl dyn Error + Send + Sync {
755 #[stable(feature = "error_downcast", since = "1.3.0")]
756 /// Attempts to downcast the box to a concrete type.
757 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
758 let err: Box<dyn Error> = self;
759 <dyn Error>::downcast(err).map_err(|s| unsafe {
760 // Reapply the `Send + Sync` marker.
761 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
771 #[derive(Debug, PartialEq)]
773 #[derive(Debug, PartialEq)]
776 impl fmt::Display for A {
777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781 impl fmt::Display for B {
782 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
793 let a = &mut a as &mut (dyn Error + 'static);
794 assert_eq!(a.downcast_ref::<A>(), Some(&A));
795 assert_eq!(a.downcast_ref::<B>(), None);
796 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
797 assert_eq!(a.downcast_mut::<B>(), None);
799 let a: Box<dyn Error> = Box::new(A);
800 match a.downcast::<B>() {
801 Ok(..) => panic!("expected error"),
802 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),