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>`].
38 /// Errors must describe themselves through the [`Display`] and [`Debug`]
39 /// traits. Error messages are typically concise lowercase sentences without
40 /// trailing punctuation:
43 /// let err = "NaN".parse::<u32>().unwrap_err();
44 /// assert_eq!(err.to_string(), "invalid digit found in string");
47 /// Errors may provide cause chain information. [`Error::source()`] is generally
48 /// used when errors cross "abstraction boundaries". If one module must report
49 /// an error that is caused by an error from a lower-level module, it can allow
50 /// accessing that error via [`Error::source()`]. This makes it possible for the
51 /// high-level module to provide its own errors while also revealing some of the
52 /// implementation for debugging via `source` chains.
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub trait Error
: Debug
+ Display
{
55 /// The lower-level source of this error, if any.
60 /// use std::error::Error;
64 /// struct SuperError {
65 /// side: SuperErrorSideKick,
68 /// impl fmt::Display for SuperError {
69 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 /// write!(f, "SuperError is here!")
74 /// impl Error for SuperError {
75 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
81 /// struct SuperErrorSideKick;
83 /// impl fmt::Display for SuperErrorSideKick {
84 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 /// write!(f, "SuperErrorSideKick is here!")
89 /// impl Error for SuperErrorSideKick {}
91 /// fn get_super_error() -> Result<(), SuperError> {
92 /// Err(SuperError { side: SuperErrorSideKick })
96 /// match get_super_error() {
98 /// println!("Error: {}", e);
99 /// println!("Caused by: {}", e.source().unwrap());
101 /// _ => println!("No error"),
105 #[stable(feature = "error_source", since = "1.30.0")]
106 fn source(&self) -> Option
<&(dyn Error
+ '
static)> {
110 /// Gets the `TypeId` of `self`.
113 feature
= "error_type_id",
114 reason
= "this is memory-unsafe to override in user code",
117 fn type_id(&self, _
: private
::Internal
) -> TypeId
124 /// Returns a stack backtrace, if available, of where this error occurred.
126 /// This function allows inspecting the location, in code, of where an error
127 /// happened. The returned `Backtrace` contains information about the stack
128 /// trace of the OS thread of execution of where the error originated from.
130 /// Note that not all errors contain a `Backtrace`. Also note that a
131 /// `Backtrace` may actually be empty. For more information consult the
132 /// `Backtrace` type itself.
133 #[unstable(feature = "backtrace", issue = "53487")]
134 fn backtrace(&self) -> Option
<&Backtrace
> {
139 /// if let Err(e) = "xc".parse::<u32>() {
140 /// // Print `e` itself, no need for description().
141 /// eprintln!("Error: {}", e);
144 #[stable(feature = "rust1", since = "1.0.0")]
145 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
146 fn description(&self) -> &str {
147 "description() is deprecated; use Display"
150 #[stable(feature = "rust1", since = "1.0.0")]
153 reason
= "replaced by Error::source, which can support downcasting"
155 #[allow(missing_docs)]
156 fn cause(&self) -> Option
<&dyn Error
> {
162 // This is a hack to prevent `type_id` from being overridden by `Error`
163 // implementations, since that can enable unsound downcasting.
164 #[unstable(feature = "error_type_id", issue = "60784")]
169 #[stable(feature = "rust1", since = "1.0.0")]
170 impl<'a
, E
: Error
+ 'a
> From
<E
> for Box
<dyn Error
+ 'a
> {
171 /// Converts a type of [`Error`] into a box of dyn [`Error`].
176 /// use std::error::Error;
183 /// impl fmt::Display for AnError {
184 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 /// write!(f , "An error")
189 /// impl Error for AnError {}
191 /// let an_error = AnError;
192 /// assert!(0 == mem::size_of_val(&an_error));
193 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
194 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
196 fn from(err
: E
) -> Box
<dyn Error
+ 'a
> {
201 #[stable(feature = "rust1", since = "1.0.0")]
202 impl<'a
, E
: Error
+ Send
+ Sync
+ 'a
> From
<E
> for Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
203 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
204 /// dyn [`Error`] + [`Send`] + [`Sync`].
209 /// use std::error::Error;
216 /// impl fmt::Display for AnError {
217 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 /// write!(f , "An error")
222 /// impl Error for AnError {}
224 /// unsafe impl Send for AnError {}
226 /// unsafe impl Sync for AnError {}
228 /// let an_error = AnError;
229 /// assert!(0 == mem::size_of_val(&an_error));
230 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
232 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
234 fn from(err
: E
) -> Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
239 #[stable(feature = "rust1", since = "1.0.0")]
240 impl From
<String
> for Box
<dyn Error
+ Send
+ Sync
> {
241 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
246 /// use std::error::Error;
249 /// let a_string_error = "a string error".to_string();
250 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
252 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
255 fn from(err
: String
) -> Box
<dyn Error
+ Send
+ Sync
> {
256 struct StringError(String
);
258 impl Error
for StringError
{
260 fn description(&self) -> &str {
265 impl Display
for StringError
{
266 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
267 Display
::fmt(&self.0, f
)
271 // Purposefully skip printing "StringError(..)"
272 impl Debug
for StringError
{
273 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
274 Debug
::fmt(&self.0, f
)
278 Box
::new(StringError(err
))
282 #[stable(feature = "string_box_error", since = "1.6.0")]
283 impl From
<String
> for Box
<dyn Error
> {
284 /// Converts a [`String`] into a box of dyn [`Error`].
289 /// use std::error::Error;
292 /// let a_string_error = "a string error".to_string();
293 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
294 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
296 fn from(str_err
: String
) -> Box
<dyn Error
> {
297 let err1
: Box
<dyn Error
+ Send
+ Sync
> = From
::from(str_err
);
298 let err2
: Box
<dyn Error
> = err1
;
303 #[stable(feature = "rust1", since = "1.0.0")]
304 impl<'a
> From
<&str> for Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
305 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
307 /// [`str`]: prim@str
312 /// use std::error::Error;
315 /// let a_str_error = "a str error";
316 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
318 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
321 fn from(err
: &str) -> Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
322 From
::from(String
::from(err
))
326 #[stable(feature = "string_box_error", since = "1.6.0")]
327 impl From
<&str> for Box
<dyn Error
> {
328 /// Converts a [`str`] into a box of dyn [`Error`].
330 /// [`str`]: prim@str
335 /// use std::error::Error;
338 /// let a_str_error = "a str error";
339 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
340 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
342 fn from(err
: &str) -> Box
<dyn Error
> {
343 From
::from(String
::from(err
))
347 #[stable(feature = "cow_box_error", since = "1.22.0")]
348 impl<'a
, 'b
> From
<Cow
<'b
, str>> for Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
349 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
354 /// use std::error::Error;
356 /// use std::borrow::Cow;
358 /// let a_cow_str_error = Cow::from("a str error");
359 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
361 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
363 fn from(err
: Cow
<'b
, str>) -> Box
<dyn Error
+ Send
+ Sync
+ 'a
> {
364 From
::from(String
::from(err
))
368 #[stable(feature = "cow_box_error", since = "1.22.0")]
369 impl<'a
> From
<Cow
<'a
, str>> for Box
<dyn Error
> {
370 /// Converts a [`Cow`] into a box of dyn [`Error`].
375 /// use std::error::Error;
377 /// use std::borrow::Cow;
379 /// let a_cow_str_error = Cow::from("a str error");
380 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
381 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
383 fn from(err
: Cow
<'a
, str>) -> Box
<dyn Error
> {
384 From
::from(String
::from(err
))
388 #[unstable(feature = "never_type", issue = "35121")]
392 feature
= "allocator_api",
393 reason
= "the precise API and guarantees it provides may be tweaked.",
396 impl Error
for AllocError {}
398 #[stable(feature = "alloc_layout", since = "1.28.0")]
399 impl Error
for LayoutError {}
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl Error
for str::ParseBoolError
{
404 fn description(&self) -> &str {
405 "failed to parse bool"
409 #[stable(feature = "rust1", since = "1.0.0")]
410 impl Error
for str::Utf8Error
{
412 fn description(&self) -> &str {
413 "invalid utf-8: corrupt contents"
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl Error
for num
::ParseIntError
{
420 fn description(&self) -> &str {
425 #[stable(feature = "try_from", since = "1.34.0")]
426 impl Error
for num
::TryFromIntError
{
428 fn description(&self) -> &str {
433 #[stable(feature = "try_from", since = "1.34.0")]
434 impl Error
for array
::TryFromSliceError
{
436 fn description(&self) -> &str {
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl Error
for num
::ParseFloatError
{
444 fn description(&self) -> &str {
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl Error
for string
::FromUtf8Error
{
452 fn description(&self) -> &str {
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Error
for string
::FromUtf16Error
{
460 fn description(&self) -> &str {
465 #[stable(feature = "str_parse_error2", since = "1.8.0")]
466 impl Error
for Infallible
{
467 fn description(&self) -> &str {
472 #[stable(feature = "decode_utf16", since = "1.9.0")]
473 impl Error
for char::DecodeUtf16Error
{
475 fn description(&self) -> &str {
476 "unpaired surrogate found"
480 #[unstable(feature = "map_try_insert", issue = "82766")]
481 impl<'a
, K
: Debug
+ Ord
, V
: Debug
> Error
482 for crate::collections
::btree_map
::OccupiedError
<'a
, K
, V
>
485 fn description(&self) -> &str {
490 #[unstable(feature = "map_try_insert", issue = "82766")]
491 impl<'a
, K
: Debug
, V
: Debug
> Error
for crate::collections
::hash_map
::OccupiedError
<'a
, K
, V
> {
493 fn description(&self) -> &str {
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 = "error_by_ref", since = "1.51.0")]
516 impl<'a
, T
: Error
+ ?Sized
> Error
for &'a T
{
517 #[allow(deprecated, deprecated_in_future)]
518 fn description(&self) -> &str {
519 Error
::description(&**self)
523 fn cause(&self) -> Option
<&dyn Error
> {
524 Error
::cause(&**self)
527 fn source(&self) -> Option
<&(dyn Error
+ '
static)> {
528 Error
::source(&**self)
531 fn backtrace(&self) -> Option
<&Backtrace
> {
532 Error
::backtrace(&**self)
536 #[stable(feature = "arc_error", since = "1.52.0")]
537 impl<T
: Error
+ ?Sized
> Error
for Arc
<T
> {
538 #[allow(deprecated, deprecated_in_future)]
539 fn description(&self) -> &str {
540 Error
::description(&**self)
544 fn cause(&self) -> Option
<&dyn Error
> {
545 Error
::cause(&**self)
548 fn source(&self) -> Option
<&(dyn Error
+ '
static)> {
549 Error
::source(&**self)
552 fn backtrace(&self) -> Option
<&Backtrace
> {
553 Error
::backtrace(&**self)
557 #[stable(feature = "fmt_error", since = "1.11.0")]
558 impl Error
for fmt
::Error
{
560 fn description(&self) -> &str {
561 "an error occurred when formatting an argument"
565 #[stable(feature = "try_borrow", since = "1.13.0")]
566 impl Error
for cell
::BorrowError
{
568 fn description(&self) -> &str {
569 "already mutably borrowed"
573 #[stable(feature = "try_borrow", since = "1.13.0")]
574 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
{
584 fn description(&self) -> &str {
585 "converted integer out of range for `char`"
589 #[stable(feature = "char_from_str", since = "1.20.0")]
590 impl Error
for char::ParseCharError
{
592 fn description(&self) -> &str {
597 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
598 impl Error
for alloc
::collections
::TryReserveError {}
600 #[unstable(feature = "duration_checked_float", issue = "83400")]
601 impl Error
for core
::time
::FromSecsError {}
603 // Copied from `any.rs`.
604 impl dyn Error
+ '
static {
605 /// Returns `true` if the boxed type is the same as `T`
606 #[stable(feature = "error_downcast", since = "1.3.0")]
608 pub fn is
<T
: Error
+ '
static>(&self) -> bool
{
609 // Get `TypeId` of the type this function is instantiated with.
610 let t
= TypeId
::of
::<T
>();
612 // Get `TypeId` of the type in the trait object.
613 let boxed
= self.type_id(private
::Internal
);
615 // Compare both `TypeId`s on equality.
619 /// Returns some reference to the boxed value if it is of type `T`, or
620 /// `None` if it isn't.
621 #[stable(feature = "error_downcast", since = "1.3.0")]
623 pub fn downcast_ref
<T
: Error
+ '
static>(&self) -> Option
<&T
> {
625 unsafe { Some(&*(self as *const dyn Error as *const T)) }
631 /// Returns some mutable reference to the boxed value if it is of type `T`, or
632 /// `None` if it isn't.
633 #[stable(feature = "error_downcast", since = "1.3.0")]
635 pub fn downcast_mut
<T
: Error
+ '
static>(&mut self) -> Option
<&mut T
> {
637 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
644 impl dyn Error
+ '
static + Send
{
645 /// Forwards to the method defined on the type `dyn Error`.
646 #[stable(feature = "error_downcast", since = "1.3.0")]
648 pub fn is
<T
: Error
+ '
static>(&self) -> bool
{
649 <dyn Error
+ '
static>::is
::<T
>(self)
652 /// Forwards to the method defined on the type `dyn Error`.
653 #[stable(feature = "error_downcast", since = "1.3.0")]
655 pub fn downcast_ref
<T
: Error
+ '
static>(&self) -> Option
<&T
> {
656 <dyn Error
+ '
static>::downcast_ref
::<T
>(self)
659 /// Forwards to the method defined on the type `dyn Error`.
660 #[stable(feature = "error_downcast", since = "1.3.0")]
662 pub fn downcast_mut
<T
: Error
+ '
static>(&mut self) -> Option
<&mut T
> {
663 <dyn Error
+ '
static>::downcast_mut
::<T
>(self)
667 impl dyn Error
+ '
static + Send
+ Sync
{
668 /// Forwards to the method defined on the type `dyn Error`.
669 #[stable(feature = "error_downcast", since = "1.3.0")]
671 pub fn is
<T
: Error
+ '
static>(&self) -> bool
{
672 <dyn Error
+ '
static>::is
::<T
>(self)
675 /// Forwards to the method defined on the type `dyn Error`.
676 #[stable(feature = "error_downcast", since = "1.3.0")]
678 pub fn downcast_ref
<T
: Error
+ '
static>(&self) -> Option
<&T
> {
679 <dyn Error
+ '
static>::downcast_ref
::<T
>(self)
682 /// Forwards to the method defined on the type `dyn Error`.
683 #[stable(feature = "error_downcast", since = "1.3.0")]
685 pub fn downcast_mut
<T
: Error
+ '
static>(&mut self) -> Option
<&mut T
> {
686 <dyn Error
+ '
static>::downcast_mut
::<T
>(self)
692 #[stable(feature = "error_downcast", since = "1.3.0")]
693 /// Attempts to downcast the box to a concrete type.
694 pub fn downcast
<T
: Error
+ '
static>(self: Box
<Self>) -> Result
<Box
<T
>, Box
<dyn Error
>> {
697 let raw
: *mut dyn Error
= Box
::into_raw(self);
698 Ok(Box
::from_raw(raw
as *mut T
))
705 /// Returns an iterator starting with the current error and continuing with
706 /// recursively calling [`Error::source`].
708 /// If you want to omit the current error and only use its sources,
714 /// #![feature(error_iter)]
715 /// use std::error::Error;
722 /// struct B(Option<Box<dyn Error + 'static>>);
724 /// impl fmt::Display for A {
725 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
730 /// impl fmt::Display for B {
731 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 /// impl Error for A {}
738 /// impl Error for B {
739 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
740 /// self.0.as_ref().map(|e| e.as_ref())
744 /// let b = B(Some(Box::new(A)));
746 /// // let err : Box<Error> = b.into(); // or
747 /// let err = &b as &(dyn Error);
749 /// let mut iter = err.chain();
751 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
752 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
753 /// assert!(iter.next().is_none());
754 /// assert!(iter.next().is_none());
756 #[unstable(feature = "error_iter", issue = "58520")]
758 pub fn chain(&self) -> Chain
<'_
> {
759 Chain { current: Some(self) }
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)`.
767 #[unstable(feature = "error_iter", issue = "58520")]
768 #[derive(Clone, Debug)]
769 pub struct Chain
<'a
> {
770 current
: Option
<&'
a (dyn Error
+ '
static)>,
773 #[unstable(feature = "error_iter", issue = "58520")]
774 impl<'a
> Iterator
for Chain
<'a
> {
775 type Item
= &'
a (dyn Error
+ '
static);
777 fn next(&mut self) -> Option
<Self::Item
> {
778 let current
= self.current
;
779 self.current
= self.current
.and_then(Error
::source
);
784 impl dyn Error
+ Send
{
786 #[stable(feature = "error_downcast", since = "1.3.0")]
787 /// Attempts to downcast the box to a concrete type.
788 pub fn downcast
<T
: Error
+ '
static>(self: Box
<Self>) -> Result
<Box
<T
>, Box
<dyn Error
+ Send
>> {
789 let err
: Box
<dyn Error
> = self;
790 <dyn Error
>::downcast(err
).map_err(|s
| unsafe {
791 // Reapply the `Send` marker.
792 transmute
::<Box
<dyn Error
>, Box
<dyn Error
+ Send
>>(s
)
797 impl dyn Error
+ Send
+ Sync
{
799 #[stable(feature = "error_downcast", since = "1.3.0")]
800 /// Attempts to downcast the box to a concrete type.
801 pub fn downcast
<T
: Error
+ '
static>(self: Box
<Self>) -> Result
<Box
<T
>, Box
<Self>> {
802 let err
: Box
<dyn Error
> = self;
803 <dyn Error
>::downcast(err
).map_err(|s
| unsafe {
804 // Reapply the `Send + Sync` marker.
805 transmute
::<Box
<dyn Error
>, Box
<dyn Error
+ Send
+ Sync
>>(s
)