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.
16 use alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
22 use fmt::{self, Debug, Display};
28 /// `Error` is a trait representing the basic expectations for error values,
29 /// i.e., values of type `E` in [`Result<T, E>`]. Errors must describe
30 /// themselves through the [`Display`] and [`Debug`] traits, and may provide
31 /// cause chain information:
33 /// The [`source`] method is generally used when errors cross "abstraction
34 /// boundaries". If one module must report an error that is caused by an error
35 /// from a lower-level module, it can allow access to that error via the
36 /// [`source`] method. This makes it possible for the high-level module to
37 /// provide its own errors while also revealing some of the implementation for
38 /// debugging via [`source`] chains.
40 /// [`Result<T, E>`]: ../result/enum.Result.html
41 /// [`Display`]: ../fmt/trait.Display.html
42 /// [`Debug`]: ../fmt/trait.Debug.html
43 /// [`source`]: trait.Error.html#method.source
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub trait Error: Debug + Display {
46 /// **This method is soft-deprecated.**
48 /// Although using it won’t cause compilation warning,
49 /// new code should use [`Display`] instead
50 /// and new `impl`s can omit it.
52 /// To obtain error description as a string, use `to_string()`.
54 /// [`Display`]: ../fmt/trait.Display.html
59 /// match "xc".parse::<u32>() {
61 /// // Print `e` itself, not `e.description()`.
62 /// println!("Error: {}", e);
64 /// _ => println!("No error"),
67 #[stable(feature = "rust1", since = "1.0.0")]
68 fn description(&self) -> &str {
69 "description() is deprecated; use Display"
72 /// The lower-level cause of this error, if any.
77 /// use std::error::Error;
81 /// struct SuperError {
82 /// side: SuperErrorSideKick,
85 /// impl fmt::Display for SuperError {
86 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
87 /// write!(f, "SuperError is here!")
91 /// impl Error for SuperError {
92 /// fn description(&self) -> &str {
93 /// "I'm the superhero of errors"
96 /// fn cause(&self) -> Option<&Error> {
102 /// struct SuperErrorSideKick;
104 /// impl fmt::Display for SuperErrorSideKick {
105 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106 /// write!(f, "SuperErrorSideKick is here!")
110 /// impl Error for SuperErrorSideKick {
111 /// fn description(&self) -> &str {
112 /// "I'm SuperError side kick"
116 /// fn get_super_error() -> Result<(), SuperError> {
117 /// Err(SuperError { side: SuperErrorSideKick })
121 /// match get_super_error() {
123 /// println!("Error: {}", e.description());
124 /// println!("Caused by: {}", e.cause().unwrap());
126 /// _ => println!("No error"),
130 #[stable(feature = "rust1", since = "1.0.0")]
131 #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
133 fn cause(&self) -> Option<&dyn Error> {
137 /// The lower-level source of this error, if any.
142 /// use std::error::Error;
146 /// struct SuperError {
147 /// side: SuperErrorSideKick,
150 /// impl fmt::Display for SuperError {
151 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
152 /// write!(f, "SuperError is here!")
156 /// impl Error for SuperError {
157 /// fn description(&self) -> &str {
158 /// "I'm the superhero of errors"
161 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
167 /// struct SuperErrorSideKick;
169 /// impl fmt::Display for SuperErrorSideKick {
170 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171 /// write!(f, "SuperErrorSideKick is here!")
175 /// impl Error for SuperErrorSideKick {
176 /// fn description(&self) -> &str {
177 /// "I'm SuperError side kick"
181 /// fn get_super_error() -> Result<(), SuperError> {
182 /// Err(SuperError { side: SuperErrorSideKick })
186 /// match get_super_error() {
188 /// println!("Error: {}", e.description());
189 /// println!("Caused by: {}", e.source().unwrap());
191 /// _ => println!("No error"),
195 #[stable(feature = "error_source", since = "1.30.0")]
196 fn source(&self) -> Option<&(dyn Error + 'static)> { None }
198 /// Get the `TypeId` of `self`
200 #[unstable(feature = "error_type_id",
201 reason = "unclear whether to commit to this public implementation detail",
203 fn type_id(&self) -> TypeId where Self: 'static {
208 #[stable(feature = "rust1", since = "1.0.0")]
209 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
210 /// Converts a type of [`Error`] into a box of dyn [`Error`].
215 /// use std::error::Error;
222 /// impl fmt::Display for AnError {
223 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
224 /// write!(f , "An error")
228 /// impl Error for AnError {
229 /// fn description(&self) -> &str {
230 /// "Description of an error"
234 /// let an_error = AnError;
235 /// assert!(0 == mem::size_of_val(&an_error));
236 /// let a_boxed_error = Box::<Error>::from(an_error);
237 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
239 fn from(err: E) -> Box<dyn Error + 'a> {
244 #[stable(feature = "rust1", since = "1.0.0")]
245 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
246 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of dyn [`Error`] +
247 /// [`Send`] + [`Sync`].
252 /// use std::error::Error;
259 /// impl fmt::Display for AnError {
260 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
261 /// write!(f , "An error")
265 /// impl Error for AnError {
266 /// fn description(&self) -> &str {
267 /// "Description of an error"
271 /// unsafe impl Send for AnError {}
273 /// unsafe impl Sync for AnError {}
275 /// let an_error = AnError;
276 /// assert!(0 == mem::size_of_val(&an_error));
277 /// let a_boxed_error = Box::<Error + Send + Sync>::from(an_error);
279 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
281 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
286 #[stable(feature = "rust1", since = "1.0.0")]
287 impl From<String> for Box<dyn Error + Send + Sync> {
288 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
293 /// use std::error::Error;
296 /// let a_string_error = "a string error".to_string();
297 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_string_error);
299 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
301 fn from(err: String) -> Box<dyn Error + Send + Sync> {
303 struct StringError(String);
305 impl Error for StringError {
306 fn description(&self) -> &str { &self.0 }
309 impl Display for StringError {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 Display::fmt(&self.0, f)
315 Box::new(StringError(err))
319 #[stable(feature = "string_box_error", since = "1.6.0")]
320 impl From<String> for Box<dyn Error> {
321 /// Converts a [`String`] into a box of dyn [`Error`].
326 /// use std::error::Error;
329 /// let a_string_error = "a string error".to_string();
330 /// let a_boxed_error = Box::<Error>::from(a_string_error);
331 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
333 fn from(str_err: String) -> Box<dyn Error> {
334 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
335 let err2: Box<dyn Error> = err1;
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<'a, 'b> From<&'b str> for Box<dyn Error + Send + Sync + 'a> {
342 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
347 /// use std::error::Error;
350 /// let a_str_error = "a str error";
351 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_str_error);
353 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
355 fn from(err: &'b str) -> Box<dyn Error + Send + Sync + 'a> {
356 From::from(String::from(err))
360 #[stable(feature = "string_box_error", since = "1.6.0")]
361 impl<'a> From<&'a str> for Box<dyn Error> {
362 /// Converts a [`str`] into a box of dyn [`Error`].
367 /// use std::error::Error;
370 /// let a_str_error = "a str error";
371 /// let a_boxed_error = Box::<Error>::from(a_str_error);
372 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
374 fn from(err: &'a str) -> Box<dyn Error> {
375 From::from(String::from(err))
379 #[stable(feature = "cow_box_error", since = "1.22.0")]
380 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
381 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
386 /// use std::error::Error;
388 /// use std::borrow::Cow;
390 /// let a_cow_str_error = Cow::from("a str error");
391 /// let a_boxed_error = Box::<Error + Send + Sync>::from(a_cow_str_error);
393 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
395 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
396 From::from(String::from(err))
400 #[stable(feature = "cow_box_error", since = "1.22.0")]
401 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
402 /// Converts a [`Cow`] into a box of dyn [`Error`].
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::<Error>::from(a_cow_str_error);
413 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
415 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
416 From::from(String::from(err))
420 #[unstable(feature = "never_type", issue = "35121")]
422 fn description(&self) -> &str { *self }
425 #[unstable(feature = "allocator_api",
426 reason = "the precise API and guarantees it provides may be tweaked.",
428 impl Error for AllocErr {
429 fn description(&self) -> &str {
430 "memory allocation failed"
434 #[unstable(feature = "allocator_api",
435 reason = "the precise API and guarantees it provides may be tweaked.",
437 impl Error for LayoutErr {
438 fn description(&self) -> &str {
439 "invalid parameters to Layout::from_size_align"
443 #[unstable(feature = "allocator_api",
444 reason = "the precise API and guarantees it provides may be tweaked.",
446 impl Error for CannotReallocInPlace {
447 fn description(&self) -> &str {
448 CannotReallocInPlace::description(self)
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl Error for str::ParseBoolError {
454 fn description(&self) -> &str { "failed to parse bool" }
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Error for str::Utf8Error {
459 fn description(&self) -> &str {
460 "invalid utf-8: corrupt contents"
464 #[stable(feature = "rust1", since = "1.0.0")]
465 impl Error for num::ParseIntError {
466 fn description(&self) -> &str {
471 #[unstable(feature = "try_from", issue = "33417")]
472 impl Error for num::TryFromIntError {
473 fn description(&self) -> &str {
478 #[unstable(feature = "try_from", issue = "33417")]
479 impl Error for array::TryFromSliceError {
480 fn description(&self) -> &str {
485 #[stable(feature = "rust1", since = "1.0.0")]
486 impl Error for num::ParseFloatError {
487 fn description(&self) -> &str {
492 #[stable(feature = "rust1", since = "1.0.0")]
493 impl Error for string::FromUtf8Error {
494 fn description(&self) -> &str {
499 #[stable(feature = "rust1", since = "1.0.0")]
500 impl Error for string::FromUtf16Error {
501 fn description(&self) -> &str {
506 #[stable(feature = "str_parse_error2", since = "1.8.0")]
507 impl Error for string::ParseError {
508 fn description(&self) -> &str {
513 #[stable(feature = "decode_utf16", since = "1.9.0")]
514 impl Error for char::DecodeUtf16Error {
515 fn description(&self) -> &str {
516 "unpaired surrogate found"
520 #[stable(feature = "box_error", since = "1.8.0")]
521 impl<T: Error> Error for Box<T> {
522 fn description(&self) -> &str {
523 Error::description(&**self)
527 fn cause(&self) -> Option<&dyn Error> {
528 Error::cause(&**self)
532 #[stable(feature = "fmt_error", since = "1.11.0")]
533 impl Error for fmt::Error {
534 fn description(&self) -> &str {
535 "an error occurred when formatting an argument"
539 #[stable(feature = "try_borrow", since = "1.13.0")]
540 impl Error for cell::BorrowError {
541 fn description(&self) -> &str {
542 "already mutably borrowed"
546 #[stable(feature = "try_borrow", since = "1.13.0")]
547 impl Error for cell::BorrowMutError {
548 fn description(&self) -> &str {
553 #[unstable(feature = "try_from", issue = "33417")]
554 impl Error for char::CharTryFromError {
555 fn description(&self) -> &str {
556 "converted integer out of range for `char`"
560 #[stable(feature = "char_from_str", since = "1.20.0")]
561 impl Error for char::ParseCharError {
562 fn description(&self) -> &str {
567 // copied from any.rs
568 impl dyn Error + 'static {
569 /// Returns true if the boxed type is the same as `T`
570 #[stable(feature = "error_downcast", since = "1.3.0")]
572 pub fn is<T: Error + 'static>(&self) -> bool {
573 // Get TypeId of the type this function is instantiated with
574 let t = TypeId::of::<T>();
576 // Get TypeId of the type in the trait object
577 let boxed = self.type_id();
579 // Compare both TypeIds on equality
583 /// Returns some 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_ref<T: Error + 'static>(&self) -> Option<&T> {
590 Some(&*(self as *const dyn Error as *const T))
597 /// Returns some mutable reference to the boxed value if it is of type `T`, or
598 /// `None` if it isn't.
599 #[stable(feature = "error_downcast", since = "1.3.0")]
601 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
604 Some(&mut *(self as *mut dyn Error as *mut T))
612 impl dyn Error + 'static + Send {
613 /// Forwards to the method defined on the type `Any`.
614 #[stable(feature = "error_downcast", since = "1.3.0")]
616 pub fn is<T: Error + 'static>(&self) -> bool {
617 <dyn Error + 'static>::is::<T>(self)
620 /// Forwards to the method defined on the type `Any`.
621 #[stable(feature = "error_downcast", since = "1.3.0")]
623 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
624 <dyn Error + 'static>::downcast_ref::<T>(self)
627 /// Forwards to the method defined on the type `Any`.
628 #[stable(feature = "error_downcast", since = "1.3.0")]
630 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
631 <dyn Error + 'static>::downcast_mut::<T>(self)
635 impl dyn Error + 'static + Send + Sync {
636 /// Forwards to the method defined on the type `Any`.
637 #[stable(feature = "error_downcast", since = "1.3.0")]
639 pub fn is<T: Error + 'static>(&self) -> bool {
640 <dyn Error + 'static>::is::<T>(self)
643 /// Forwards to the method defined on the type `Any`.
644 #[stable(feature = "error_downcast", since = "1.3.0")]
646 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
647 <dyn Error + 'static>::downcast_ref::<T>(self)
650 /// Forwards to the method defined on the type `Any`.
651 #[stable(feature = "error_downcast", since = "1.3.0")]
653 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
654 <dyn Error + 'static>::downcast_mut::<T>(self)
660 #[stable(feature = "error_downcast", since = "1.3.0")]
661 /// Attempt to downcast the box to a concrete type.
662 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
665 let raw: *mut dyn Error = Box::into_raw(self);
666 Ok(Box::from_raw(raw as *mut T))
674 impl dyn Error + Send {
676 #[stable(feature = "error_downcast", since = "1.3.0")]
677 /// Attempt to downcast the box to a concrete type.
678 pub fn downcast<T: Error + 'static>(self: Box<Self>)
679 -> Result<Box<T>, Box<dyn Error + Send>> {
680 let err: Box<dyn Error> = self;
681 <dyn Error>::downcast(err).map_err(|s| unsafe {
682 // reapply the Send marker
683 transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
688 impl dyn Error + Send + Sync {
690 #[stable(feature = "error_downcast", since = "1.3.0")]
691 /// Attempt to downcast the box to a concrete type.
692 pub fn downcast<T: Error + 'static>(self: Box<Self>)
693 -> Result<Box<T>, Box<Self>> {
694 let err: Box<dyn Error> = self;
695 <dyn Error>::downcast(err).map_err(|s| unsafe {
696 // reapply the Send+Sync marker
697 transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
707 #[derive(Debug, PartialEq)]
709 #[derive(Debug, PartialEq)]
712 impl fmt::Display for A {
713 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
717 impl fmt::Display for B {
718 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
724 fn description(&self) -> &str { "A-desc" }
727 fn description(&self) -> &str { "A-desc" }
733 let a = &mut a as &mut (dyn Error + 'static);
734 assert_eq!(a.downcast_ref::<A>(), Some(&A));
735 assert_eq!(a.downcast_ref::<B>(), None);
736 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
737 assert_eq!(a.downcast_mut::<B>(), None);
739 let a: Box<dyn Error> = Box::new(A);
740 match a.downcast::<B>() {
741 Ok(..) => panic!("expected error"),
742 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),