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, LayoutErr, CannotReallocInPlace};
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 /// **This method is soft-deprecated.**
50 /// Although using it won’t cause compilation warning,
51 /// new code should use [`Display`] instead
52 /// and new `impl`s can omit it.
54 /// To obtain error description as a string, use `to_string()`.
56 /// [`Display`]: ../fmt/trait.Display.html
61 /// match "xc".parse::<u32>() {
63 /// // Print `e` itself, not `e.description()`.
64 /// println!("Error: {}", e);
66 /// _ => println!("No error"),
69 #[stable(feature = "rust1", since = "1.0.0")]
70 fn description(&self) -> &str {
71 "description() is deprecated; use Display"
74 /// The lower-level cause of this error, if any.
79 /// use std::error::Error;
83 /// struct SuperError {
84 /// side: SuperErrorSideKick,
87 /// impl fmt::Display for SuperError {
88 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 /// write!(f, "SuperError is here!")
93 /// impl Error for SuperError {
94 /// fn cause(&self) -> Option<&dyn Error> {
100 /// struct SuperErrorSideKick;
102 /// impl fmt::Display for SuperErrorSideKick {
103 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104 /// write!(f, "SuperErrorSideKick is here!")
108 /// impl Error for SuperErrorSideKick {}
110 /// fn get_super_error() -> Result<(), SuperError> {
111 /// Err(SuperError { side: SuperErrorSideKick })
115 /// match get_super_error() {
117 /// println!("Error: {}", e.description());
118 /// println!("Caused by: {}", e.cause().unwrap());
120 /// _ => println!("No error"),
124 #[stable(feature = "rust1", since = "1.0.0")]
125 #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
127 fn cause(&self) -> Option<&dyn Error> {
131 /// The lower-level source of this error, if any.
136 /// use std::error::Error;
140 /// struct SuperError {
141 /// side: SuperErrorSideKick,
144 /// impl fmt::Display for SuperError {
145 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 /// write!(f, "SuperError is here!")
150 /// impl Error for SuperError {
151 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
157 /// struct SuperErrorSideKick;
159 /// impl fmt::Display for SuperErrorSideKick {
160 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 /// write!(f, "SuperErrorSideKick is here!")
165 /// impl Error for SuperErrorSideKick {}
167 /// fn get_super_error() -> Result<(), SuperError> {
168 /// Err(SuperError { side: SuperErrorSideKick })
172 /// match get_super_error() {
174 /// println!("Error: {}", e.description());
175 /// println!("Caused by: {}", e.source().unwrap());
177 /// _ => println!("No error"),
181 #[stable(feature = "error_source", since = "1.30.0")]
182 fn source(&self) -> Option<&(dyn Error + 'static)> { None }
184 /// Gets the `TypeId` of `self`.
186 #[unstable(feature = "error_type_id",
187 reason = "this is memory-unsafe to override in user code",
189 fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
193 /// Returns a stack backtrace, if available, of where this error occurred.
195 /// This function allows inspecting the location, in code, of where an error
196 /// happened. The returned `Backtrace` contains information about the stack
197 /// trace of the OS thread of execution of where the error originated from.
199 /// Note that not all errors contain a `Backtrace`. Also note that a
200 /// `Backtrace` may actually be empty. For more information consult the
201 /// `Backtrace` type itself.
202 #[unstable(feature = "backtrace", issue = "53487")]
203 fn backtrace(&self) -> Option<&Backtrace> {
209 // This is a hack to prevent `type_id` from being overridden by `Error`
210 // implementations, since that can enable unsound downcasting.
211 #[unstable(feature = "error_type_id", issue = "60784")]
216 #[stable(feature = "rust1", since = "1.0.0")]
217 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
218 /// Converts a type of [`Error`] into a box of dyn [`Error`].
220 /// [`Error`]: ../error/trait.Error.html
225 /// use std::error::Error;
232 /// impl fmt::Display for AnError {
233 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 /// write!(f , "An error")
238 /// impl Error for AnError {}
240 /// let an_error = AnError;
241 /// assert!(0 == mem::size_of_val(&an_error));
242 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
243 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
245 fn from(err: E) -> Box<dyn Error + 'a> {
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
252 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
253 /// dyn [`Error`] + [`Send`] + [`Sync`].
255 /// [`Error`]: ../error/trait.Error.html
260 /// use std::error::Error;
267 /// impl fmt::Display for AnError {
268 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
269 /// write!(f , "An error")
273 /// impl Error for AnError {}
275 /// unsafe impl Send for AnError {}
277 /// unsafe impl Sync for AnError {}
279 /// let an_error = AnError;
280 /// assert!(0 == mem::size_of_val(&an_error));
281 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
283 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
285 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl From<String> for Box<dyn Error + Send + Sync> {
292 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
294 /// [`Error`]: ../error/trait.Error.html
299 /// use std::error::Error;
302 /// let a_string_error = "a string error".to_string();
303 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
305 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
307 fn from(err: String) -> Box<dyn Error + Send + Sync> {
308 struct StringError(String);
310 impl Error for StringError {
311 fn description(&self) -> &str { &self.0 }
314 impl Display for StringError {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 Display::fmt(&self.0, f)
320 // Purposefully skip printing "StringError(..)"
321 impl Debug for StringError {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 Debug::fmt(&self.0, f)
327 Box::new(StringError(err))
331 #[stable(feature = "string_box_error", since = "1.6.0")]
332 impl From<String> for Box<dyn Error> {
333 /// Converts a [`String`] into a box of dyn [`Error`].
335 /// [`Error`]: ../error/trait.Error.html
340 /// use std::error::Error;
343 /// let a_string_error = "a string error".to_string();
344 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
345 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
347 fn from(str_err: String) -> Box<dyn Error> {
348 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
349 let err2: Box<dyn Error> = err1;
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
356 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
358 /// [`Error`]: ../error/trait.Error.html
363 /// use std::error::Error;
366 /// let a_str_error = "a str error";
367 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
369 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
371 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
372 From::from(String::from(err))
376 #[stable(feature = "string_box_error", since = "1.6.0")]
377 impl From<&str> for Box<dyn Error> {
378 /// Converts a [`str`] into a box of dyn [`Error`].
380 /// [`Error`]: ../error/trait.Error.html
385 /// use std::error::Error;
388 /// let a_str_error = "a str error";
389 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
390 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
392 fn from(err: &str) -> Box<dyn Error> {
393 From::from(String::from(err))
397 #[stable(feature = "cow_box_error", since = "1.22.0")]
398 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
399 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
401 /// [`Cow`]: ../borrow/enum.Cow.html
402 /// [`Error`]: ../error/trait.Error.html
407 /// use std::error::Error;
409 /// use std::borrow::Cow;
411 /// let a_cow_str_error = Cow::from("a str error");
412 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
414 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
416 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
417 From::from(String::from(err))
421 #[stable(feature = "cow_box_error", since = "1.22.0")]
422 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
423 /// Converts a [`Cow`] into a box of dyn [`Error`].
425 /// [`Cow`]: ../borrow/enum.Cow.html
426 /// [`Error`]: ../error/trait.Error.html
431 /// use std::error::Error;
433 /// use std::borrow::Cow;
435 /// let a_cow_str_error = Cow::from("a str error");
436 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
437 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
439 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
440 From::from(String::from(err))
444 #[unstable(feature = "never_type", issue = "35121")]
446 fn description(&self) -> &str { *self }
449 #[unstable(feature = "allocator_api",
450 reason = "the precise API and guarantees it provides may be tweaked.",
452 impl Error for AllocErr {
453 fn description(&self) -> &str {
454 "memory allocation failed"
458 #[unstable(feature = "allocator_api",
459 reason = "the precise API and guarantees it provides may be tweaked.",
461 impl Error for LayoutErr {
462 fn description(&self) -> &str {
463 "invalid parameters to Layout::from_size_align"
467 #[unstable(feature = "allocator_api",
468 reason = "the precise API and guarantees it provides may be tweaked.",
470 impl Error for CannotReallocInPlace {
471 fn description(&self) -> &str {
472 CannotReallocInPlace::description(self)
476 #[stable(feature = "rust1", since = "1.0.0")]
477 impl Error for str::ParseBoolError {
478 fn description(&self) -> &str { "failed to parse bool" }
481 #[stable(feature = "rust1", since = "1.0.0")]
482 impl Error for str::Utf8Error {
483 fn description(&self) -> &str {
484 "invalid utf-8: corrupt contents"
488 #[stable(feature = "rust1", since = "1.0.0")]
489 impl Error for num::ParseIntError {
490 fn description(&self) -> &str {
495 #[stable(feature = "try_from", since = "1.34.0")]
496 impl Error for num::TryFromIntError {
497 fn description(&self) -> &str {
502 #[stable(feature = "try_from", since = "1.34.0")]
503 impl Error for array::TryFromSliceError {
504 fn description(&self) -> &str {
509 #[stable(feature = "rust1", since = "1.0.0")]
510 impl Error for num::ParseFloatError {
511 fn description(&self) -> &str {
516 #[stable(feature = "rust1", since = "1.0.0")]
517 impl Error for string::FromUtf8Error {
518 fn description(&self) -> &str {
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl Error for string::FromUtf16Error {
525 fn description(&self) -> &str {
530 #[stable(feature = "str_parse_error2", since = "1.8.0")]
531 impl Error for string::ParseError {
532 fn description(&self) -> &str {
537 #[stable(feature = "decode_utf16", since = "1.9.0")]
538 impl Error for char::DecodeUtf16Error {
539 fn description(&self) -> &str {
540 "unpaired surrogate found"
544 #[stable(feature = "box_error", since = "1.8.0")]
545 impl<T: Error> Error for Box<T> {
546 fn description(&self) -> &str {
547 Error::description(&**self)
551 fn cause(&self) -> Option<&dyn Error> {
552 Error::cause(&**self)
555 fn source(&self) -> Option<&(dyn Error + 'static)> {
556 Error::source(&**self)
560 #[stable(feature = "fmt_error", since = "1.11.0")]
561 impl Error for fmt::Error {
562 fn description(&self) -> &str {
563 "an error occurred when formatting an argument"
567 #[stable(feature = "try_borrow", since = "1.13.0")]
568 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 {
576 fn description(&self) -> &str {
581 #[stable(feature = "try_from", since = "1.34.0")]
582 impl Error for char::CharTryFromError {
583 fn description(&self) -> &str {
584 "converted integer out of range for `char`"
588 #[stable(feature = "char_from_str", since = "1.20.0")]
589 impl Error for char::ParseCharError {
590 fn description(&self) -> &str {
595 // Copied from `any.rs`.
596 impl dyn Error + 'static {
597 /// Returns `true` if the boxed type is the same as `T`
598 #[stable(feature = "error_downcast", since = "1.3.0")]
600 pub fn is<T: Error + 'static>(&self) -> bool {
601 // Get `TypeId` of the type this function is instantiated with.
602 let t = TypeId::of::<T>();
604 // Get `TypeId` of the type in the trait object.
605 let boxed = self.type_id(private::Internal);
607 // Compare both `TypeId`s on equality.
611 /// Returns some reference to the boxed value if it is of type `T`, or
612 /// `None` if it isn't.
613 #[stable(feature = "error_downcast", since = "1.3.0")]
615 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
618 Some(&*(self as *const dyn Error as *const T))
625 /// Returns some mutable reference to the boxed value if it is of type `T`, or
626 /// `None` if it isn't.
627 #[stable(feature = "error_downcast", since = "1.3.0")]
629 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
632 Some(&mut *(self as *mut dyn Error as *mut T))
640 impl dyn Error + 'static + Send {
641 /// Forwards to the method defined on the type `dyn Error`.
642 #[stable(feature = "error_downcast", since = "1.3.0")]
644 pub fn is<T: Error + 'static>(&self) -> bool {
645 <dyn Error + 'static>::is::<T>(self)
648 /// Forwards to the method defined on the type `dyn Error`.
649 #[stable(feature = "error_downcast", since = "1.3.0")]
651 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
652 <dyn Error + 'static>::downcast_ref::<T>(self)
655 /// Forwards to the method defined on the type `dyn Error`.
656 #[stable(feature = "error_downcast", since = "1.3.0")]
658 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
659 <dyn Error + 'static>::downcast_mut::<T>(self)
663 impl dyn Error + 'static + Send + Sync {
664 /// Forwards to the method defined on the type `dyn Error`.
665 #[stable(feature = "error_downcast", since = "1.3.0")]
667 pub fn is<T: Error + 'static>(&self) -> bool {
668 <dyn Error + 'static>::is::<T>(self)
671 /// Forwards to the method defined on the type `dyn Error`.
672 #[stable(feature = "error_downcast", since = "1.3.0")]
674 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
675 <dyn Error + 'static>::downcast_ref::<T>(self)
678 /// Forwards to the method defined on the type `dyn Error`.
679 #[stable(feature = "error_downcast", since = "1.3.0")]
681 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
682 <dyn Error + 'static>::downcast_mut::<T>(self)
688 #[stable(feature = "error_downcast", since = "1.3.0")]
689 /// Attempts to downcast the box to a concrete type.
690 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
693 let raw: *mut dyn Error = Box::into_raw(self);
694 Ok(Box::from_raw(raw as *mut T))
701 /// Returns an iterator starting with the current error and continuing with
702 /// recursively calling [`source`].
704 /// If you want to omit the current error and only use its sources,
710 /// #![feature(error_iter)]
711 /// use std::error::Error;
718 /// struct B(Option<Box<dyn Error + 'static>>);
720 /// impl fmt::Display for A {
721 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726 /// impl fmt::Display for B {
727 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 /// impl Error for A {}
734 /// impl Error for B {
735 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
736 /// self.0.as_ref().map(|e| e.as_ref())
740 /// let b = B(Some(Box::new(A)));
742 /// // let err : Box<Error> = b.into(); // or
743 /// let err = &b as &(dyn Error);
745 /// let mut iter = err.chain();
747 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
748 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
749 /// assert!(iter.next().is_none());
750 /// assert!(iter.next().is_none());
753 /// [`source`]: trait.Error.html#method.source
754 #[unstable(feature = "error_iter", issue = "58520")]
756 pub fn chain(&self) -> Chain<'_> {
763 /// An iterator over an [`Error`] and its sources.
765 /// If you want to omit the initial error and only process
766 /// its sources, use `skip(1)`.
768 /// [`Error`]: trait.Error.html
769 #[unstable(feature = "error_iter", issue = "58520")]
770 #[derive(Clone, Debug)]
771 pub struct Chain<'a> {
772 current: Option<&'a (dyn Error + 'static)>,
775 #[unstable(feature = "error_iter", issue = "58520")]
776 impl<'a> Iterator for Chain<'a> {
777 type Item = &'a (dyn Error + 'static);
779 fn next(&mut self) -> Option<Self::Item> {
780 let current = self.current;
781 self.current = self.current.and_then(Error::source);
786 impl dyn Error + Send {
788 #[stable(feature = "error_downcast", since = "1.3.0")]
789 /// Attempts to downcast the box to a concrete type.
790 pub fn downcast<T: Error + 'static>(self: Box<Self>)
791 -> Result<Box<T>, Box<dyn Error + Send>> {
792 let err: Box<dyn Error> = self;
793 <dyn Error>::downcast(err).map_err(|s| unsafe {
794 // Reapply the `Send` marker.
795 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
800 impl dyn Error + Send + Sync {
802 #[stable(feature = "error_downcast", since = "1.3.0")]
803 /// Attempts to downcast the box to a concrete type.
804 pub fn downcast<T: Error + 'static>(self: Box<Self>)
805 -> Result<Box<T>, Box<Self>> {
806 let err: Box<dyn Error> = self;
807 <dyn Error>::downcast(err).map_err(|s| unsafe {
808 // Reapply the `Send + Sync` marker.
809 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
819 #[derive(Debug, PartialEq)]
821 #[derive(Debug, PartialEq)]
824 impl fmt::Display for A {
825 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
829 impl fmt::Display for B {
830 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 fn description(&self) -> &str { "A-desc" }
839 fn description(&self) -> &str { "A-desc" }
845 let a = &mut a as &mut (dyn Error + 'static);
846 assert_eq!(a.downcast_ref::<A>(), Some(&A));
847 assert_eq!(a.downcast_ref::<B>(), None);
848 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
849 assert_eq!(a.downcast_mut::<B>(), None);
851 let a: Box<dyn Error> = Box::new(A);
852 match a.downcast::<B>() {
853 Ok(..) => panic!("expected error"),
854 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),