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;
34 /// `Error` is a trait representing the basic expectations for error values,
35 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
36 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
37 /// cause chain information:
39 /// [`Error::source()`] is generally used when errors cross
40 /// "abstraction boundaries". If one module must report an error that is caused
41 /// by an error from a lower-level module, it can allow accessing that error
42 /// via [`Error::source()`]. This makes it possible for the high-level
43 /// module to provide its own errors while also revealing some of the
44 /// implementation for debugging via `source` chains.
46 /// [`Result<T, E>`]: Result
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub trait Error: Debug + Display {
49 /// The lower-level source of this error, if any.
54 /// use std::error::Error;
58 /// struct SuperError {
59 /// side: SuperErrorSideKick,
62 /// impl fmt::Display for SuperError {
63 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 /// write!(f, "SuperError is here!")
68 /// impl Error for SuperError {
69 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
75 /// struct SuperErrorSideKick;
77 /// impl fmt::Display for SuperErrorSideKick {
78 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 /// write!(f, "SuperErrorSideKick is here!")
83 /// impl Error for SuperErrorSideKick {}
85 /// fn get_super_error() -> Result<(), SuperError> {
86 /// Err(SuperError { side: SuperErrorSideKick })
90 /// match get_super_error() {
92 /// println!("Error: {}", e);
93 /// println!("Caused by: {}", e.source().unwrap());
95 /// _ => println!("No error"),
99 #[stable(feature = "error_source", since = "1.30.0")]
100 fn source(&self) -> Option<&(dyn Error + 'static)> {
104 /// Gets the `TypeId` of `self`.
107 feature = "error_type_id",
108 reason = "this is memory-unsafe to override in user code",
111 fn type_id(&self, _: private::Internal) -> TypeId
118 /// Returns a stack backtrace, if available, of where this error occurred.
120 /// This function allows inspecting the location, in code, of where an error
121 /// happened. The returned `Backtrace` contains information about the stack
122 /// trace of the OS thread of execution of where the error originated from.
124 /// Note that not all errors contain a `Backtrace`. Also note that a
125 /// `Backtrace` may actually be empty. For more information consult the
126 /// `Backtrace` type itself.
127 #[unstable(feature = "backtrace", issue = "53487")]
128 fn backtrace(&self) -> Option<&Backtrace> {
133 /// if let Err(e) = "xc".parse::<u32>() {
134 /// // Print `e` itself, no need for description().
135 /// eprintln!("Error: {}", e);
138 #[stable(feature = "rust1", since = "1.0.0")]
139 #[rustc_deprecated(since = "1.42.0", reason = "use the Display impl or to_string()")]
140 fn description(&self) -> &str {
141 "description() is deprecated; use Display"
144 #[stable(feature = "rust1", since = "1.0.0")]
147 reason = "replaced by Error::source, which can support downcasting"
149 #[allow(missing_docs)]
150 fn cause(&self) -> Option<&dyn Error> {
156 // This is a hack to prevent `type_id` from being overridden by `Error`
157 // implementations, since that can enable unsound downcasting.
158 #[unstable(feature = "error_type_id", issue = "60784")]
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
165 /// Converts a type of [`Error`] into a box of dyn [`Error`].
170 /// use std::error::Error;
177 /// impl fmt::Display for AnError {
178 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 /// write!(f , "An error")
183 /// impl Error for AnError {}
185 /// let an_error = AnError;
186 /// assert!(0 == mem::size_of_val(&an_error));
187 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
188 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
190 fn from(err: E) -> Box<dyn Error + 'a> {
195 #[stable(feature = "rust1", since = "1.0.0")]
196 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
197 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
198 /// dyn [`Error`] + [`Send`] + [`Sync`].
203 /// use std::error::Error;
210 /// impl fmt::Display for AnError {
211 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
212 /// write!(f , "An error")
216 /// impl Error for AnError {}
218 /// unsafe impl Send for AnError {}
220 /// unsafe impl Sync for AnError {}
222 /// let an_error = AnError;
223 /// assert!(0 == mem::size_of_val(&an_error));
224 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
226 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
228 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
233 #[stable(feature = "rust1", since = "1.0.0")]
234 impl From<String> for Box<dyn Error + Send + Sync> {
235 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
240 /// use std::error::Error;
243 /// let a_string_error = "a string error".to_string();
244 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
246 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
249 fn from(err: String) -> Box<dyn Error + Send + Sync> {
250 struct StringError(String);
252 impl Error for StringError {
254 fn description(&self) -> &str {
259 impl Display for StringError {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 Display::fmt(&self.0, f)
265 // Purposefully skip printing "StringError(..)"
266 impl Debug for StringError {
267 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268 Debug::fmt(&self.0, f)
272 Box::new(StringError(err))
276 #[stable(feature = "string_box_error", since = "1.6.0")]
277 impl From<String> for Box<dyn Error> {
278 /// Converts a [`String`] into a box of dyn [`Error`].
283 /// use std::error::Error;
286 /// let a_string_error = "a string error".to_string();
287 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
288 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
290 fn from(str_err: String) -> Box<dyn Error> {
291 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
292 let err2: Box<dyn Error> = err1;
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
299 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
301 /// [`str`]: prim@str
306 /// use std::error::Error;
309 /// let a_str_error = "a str error";
310 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
312 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
315 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
316 From::from(String::from(err))
320 #[stable(feature = "string_box_error", since = "1.6.0")]
321 impl From<&str> for Box<dyn Error> {
322 /// Converts a [`str`] into a box of dyn [`Error`].
324 /// [`str`]: prim@str
329 /// use std::error::Error;
332 /// let a_str_error = "a str error";
333 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
334 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
336 fn from(err: &str) -> Box<dyn Error> {
337 From::from(String::from(err))
341 #[stable(feature = "cow_box_error", since = "1.22.0")]
342 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
343 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
348 /// use std::error::Error;
350 /// use std::borrow::Cow;
352 /// let a_cow_str_error = Cow::from("a str error");
353 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
355 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
357 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
358 From::from(String::from(err))
362 #[stable(feature = "cow_box_error", since = "1.22.0")]
363 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
364 /// Converts a [`Cow`] into a box of dyn [`Error`].
369 /// use std::error::Error;
371 /// use std::borrow::Cow;
373 /// let a_cow_str_error = Cow::from("a str error");
374 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
375 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
377 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
378 From::from(String::from(err))
382 #[unstable(feature = "never_type", issue = "35121")]
386 feature = "allocator_api",
387 reason = "the precise API and guarantees it provides may be tweaked.",
390 impl Error for AllocError {}
392 #[stable(feature = "alloc_layout", since = "1.28.0")]
393 impl Error for LayoutError {}
395 #[stable(feature = "rust1", since = "1.0.0")]
396 impl Error for str::ParseBoolError {
398 fn description(&self) -> &str {
399 "failed to parse bool"
403 #[stable(feature = "rust1", since = "1.0.0")]
404 impl Error for str::Utf8Error {
406 fn description(&self) -> &str {
407 "invalid utf-8: corrupt contents"
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl Error for num::ParseIntError {
414 fn description(&self) -> &str {
419 #[stable(feature = "try_from", since = "1.34.0")]
420 impl Error for num::TryFromIntError {
422 fn description(&self) -> &str {
427 #[stable(feature = "try_from", since = "1.34.0")]
428 impl Error for array::TryFromSliceError {
430 fn description(&self) -> &str {
435 #[stable(feature = "rust1", since = "1.0.0")]
436 impl Error for num::ParseFloatError {
438 fn description(&self) -> &str {
443 #[stable(feature = "rust1", since = "1.0.0")]
444 impl Error for string::FromUtf8Error {
446 fn description(&self) -> &str {
451 #[stable(feature = "rust1", since = "1.0.0")]
452 impl Error for string::FromUtf16Error {
454 fn description(&self) -> &str {
459 #[stable(feature = "str_parse_error2", since = "1.8.0")]
460 impl Error for Infallible {
461 fn description(&self) -> &str {
466 #[stable(feature = "decode_utf16", since = "1.9.0")]
467 impl Error for char::DecodeUtf16Error {
469 fn description(&self) -> &str {
470 "unpaired surrogate found"
474 #[stable(feature = "box_error", since = "1.8.0")]
475 impl<T: Error> Error for Box<T> {
476 #[allow(deprecated, deprecated_in_future)]
477 fn description(&self) -> &str {
478 Error::description(&**self)
482 fn cause(&self) -> Option<&dyn Error> {
483 Error::cause(&**self)
486 fn source(&self) -> Option<&(dyn Error + 'static)> {
487 Error::source(&**self)
491 #[stable(feature = "fmt_error", since = "1.11.0")]
492 impl Error for fmt::Error {
494 fn description(&self) -> &str {
495 "an error occurred when formatting an argument"
499 #[stable(feature = "try_borrow", since = "1.13.0")]
500 impl Error for cell::BorrowError {
502 fn description(&self) -> &str {
503 "already mutably borrowed"
507 #[stable(feature = "try_borrow", since = "1.13.0")]
508 impl Error for cell::BorrowMutError {
510 fn description(&self) -> &str {
515 #[stable(feature = "try_from", since = "1.34.0")]
516 impl Error for char::CharTryFromError {
518 fn description(&self) -> &str {
519 "converted integer out of range for `char`"
523 #[stable(feature = "char_from_str", since = "1.20.0")]
524 impl Error for char::ParseCharError {
526 fn description(&self) -> &str {
531 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
532 impl Error for alloc::collections::TryReserveError {}
534 // Copied from `any.rs`.
535 impl dyn Error + 'static {
536 /// Returns `true` if the boxed type is the same as `T`
537 #[stable(feature = "error_downcast", since = "1.3.0")]
539 pub fn is<T: Error + 'static>(&self) -> bool {
540 // Get `TypeId` of the type this function is instantiated with.
541 let t = TypeId::of::<T>();
543 // Get `TypeId` of the type in the trait object.
544 let boxed = self.type_id(private::Internal);
546 // Compare both `TypeId`s on equality.
550 /// Returns some reference to the boxed value if it is of type `T`, or
551 /// `None` if it isn't.
552 #[stable(feature = "error_downcast", since = "1.3.0")]
554 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
556 unsafe { Some(&*(self as *const dyn Error as *const T)) }
562 /// Returns some mutable reference to the boxed value if it is of type `T`, or
563 /// `None` if it isn't.
564 #[stable(feature = "error_downcast", since = "1.3.0")]
566 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
568 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
575 impl dyn Error + 'static + Send {
576 /// Forwards to the method defined on the type `dyn Error`.
577 #[stable(feature = "error_downcast", since = "1.3.0")]
579 pub fn is<T: Error + 'static>(&self) -> bool {
580 <dyn Error + 'static>::is::<T>(self)
583 /// Forwards to the method defined on the type `dyn Error`.
584 #[stable(feature = "error_downcast", since = "1.3.0")]
586 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
587 <dyn Error + 'static>::downcast_ref::<T>(self)
590 /// Forwards to the method defined on the type `dyn Error`.
591 #[stable(feature = "error_downcast", since = "1.3.0")]
593 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
594 <dyn Error + 'static>::downcast_mut::<T>(self)
598 impl dyn Error + 'static + Send + Sync {
599 /// Forwards to the method defined on the type `dyn Error`.
600 #[stable(feature = "error_downcast", since = "1.3.0")]
602 pub fn is<T: Error + 'static>(&self) -> bool {
603 <dyn Error + 'static>::is::<T>(self)
606 /// Forwards to the method defined on the type `dyn Error`.
607 #[stable(feature = "error_downcast", since = "1.3.0")]
609 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
610 <dyn Error + 'static>::downcast_ref::<T>(self)
613 /// Forwards to the method defined on the type `dyn Error`.
614 #[stable(feature = "error_downcast", since = "1.3.0")]
616 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
617 <dyn Error + 'static>::downcast_mut::<T>(self)
623 #[stable(feature = "error_downcast", since = "1.3.0")]
624 /// Attempts to downcast the box to a concrete type.
625 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
628 let raw: *mut dyn Error = Box::into_raw(self);
629 Ok(Box::from_raw(raw as *mut T))
636 /// Returns an iterator starting with the current error and continuing with
637 /// recursively calling [`Error::source`].
639 /// If you want to omit the current error and only use its sources,
645 /// #![feature(error_iter)]
646 /// use std::error::Error;
653 /// struct B(Option<Box<dyn Error + 'static>>);
655 /// impl fmt::Display for A {
656 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661 /// impl fmt::Display for B {
662 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
667 /// impl Error for A {}
669 /// impl Error for B {
670 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
671 /// self.0.as_ref().map(|e| e.as_ref())
675 /// let b = B(Some(Box::new(A)));
677 /// // let err : Box<Error> = b.into(); // or
678 /// let err = &b as &(dyn Error);
680 /// let mut iter = err.chain();
682 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
683 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
684 /// assert!(iter.next().is_none());
685 /// assert!(iter.next().is_none());
687 #[unstable(feature = "error_iter", issue = "58520")]
689 pub fn chain(&self) -> Chain<'_> {
690 Chain { current: Some(self) }
694 /// An iterator over an [`Error`] and its sources.
696 /// If you want to omit the initial error and only process
697 /// its sources, use `skip(1)`.
698 #[unstable(feature = "error_iter", issue = "58520")]
699 #[derive(Clone, Debug)]
700 pub struct Chain<'a> {
701 current: Option<&'a (dyn Error + 'static)>,
704 #[unstable(feature = "error_iter", issue = "58520")]
705 impl<'a> Iterator for Chain<'a> {
706 type Item = &'a (dyn Error + 'static);
708 fn next(&mut self) -> Option<Self::Item> {
709 let current = self.current;
710 self.current = self.current.and_then(Error::source);
715 impl dyn Error + Send {
717 #[stable(feature = "error_downcast", since = "1.3.0")]
718 /// Attempts to downcast the box to a concrete type.
719 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
720 let err: Box<dyn Error> = self;
721 <dyn Error>::downcast(err).map_err(|s| unsafe {
722 // Reapply the `Send` marker.
723 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
728 impl dyn Error + Send + Sync {
730 #[stable(feature = "error_downcast", since = "1.3.0")]
731 /// Attempts to downcast the box to a concrete type.
732 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
733 let err: Box<dyn Error> = self;
734 <dyn Error>::downcast(err).map_err(|s| unsafe {
735 // Reapply the `Send + Sync` marker.
736 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)