]> git.lizzy.rs Git - rust.git/blob - src/libstd/error.rs
d4c4cb9c3b997f40773c76af7ec5f971fe200fdf
[rust.git] / src / libstd / error.rs
1 //! Traits for working with Errors.
2
3 #![stable(feature = "rust1", since = "1.0.0")]
4
5 // A note about crates and the facade:
6 //
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.
15
16 use core::array;
17
18 use crate::alloc::{AllocErr, LayoutErr, CannotReallocInPlace};
19 use crate::any::TypeId;
20 use crate::backtrace::Backtrace;
21 use crate::borrow::Cow;
22 use crate::cell;
23 use crate::char;
24 use crate::fmt::{self, Debug, Display};
25 use crate::mem::transmute;
26 use crate::num;
27 use crate::str;
28 use crate::string;
29
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:
34 ///
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.
41 ///
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.**
49     ///
50     /// Although using it won’t cause compilation warning,
51     /// new code should use [`Display`] instead
52     /// and new `impl`s can omit it.
53     ///
54     /// To obtain error description as a string, use `to_string()`.
55     ///
56     /// [`Display`]: ../fmt/trait.Display.html
57     ///
58     /// # Examples
59     ///
60     /// ```
61     /// match "xc".parse::<u32>() {
62     ///     Err(e) => {
63     ///         // Print `e` itself, not `e.description()`.
64     ///         println!("Error: {}", e);
65     ///     }
66     ///     _ => println!("No error"),
67     /// }
68     /// ```
69     #[stable(feature = "rust1", since = "1.0.0")]
70     fn description(&self) -> &str {
71         "description() is deprecated; use Display"
72     }
73
74     /// The lower-level cause of this error, if any.
75     ///
76     /// # Examples
77     ///
78     /// ```
79     /// use std::error::Error;
80     /// use std::fmt;
81     ///
82     /// #[derive(Debug)]
83     /// struct SuperError {
84     ///     side: SuperErrorSideKick,
85     /// }
86     ///
87     /// impl fmt::Display for SuperError {
88     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89     ///         write!(f, "SuperError is here!")
90     ///     }
91     /// }
92     ///
93     /// impl Error for SuperError {
94     ///     fn description(&self) -> &str {
95     ///         "I'm the superhero of errors"
96     ///     }
97     ///
98     ///     fn cause(&self) -> Option<&dyn Error> {
99     ///         Some(&self.side)
100     ///     }
101     /// }
102     ///
103     /// #[derive(Debug)]
104     /// struct SuperErrorSideKick;
105     ///
106     /// impl fmt::Display for SuperErrorSideKick {
107     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108     ///         write!(f, "SuperErrorSideKick is here!")
109     ///     }
110     /// }
111     ///
112     /// impl Error for SuperErrorSideKick {
113     ///     fn description(&self) -> &str {
114     ///         "I'm SuperError side kick"
115     ///     }
116     /// }
117     ///
118     /// fn get_super_error() -> Result<(), SuperError> {
119     ///     Err(SuperError { side: SuperErrorSideKick })
120     /// }
121     ///
122     /// fn main() {
123     ///     match get_super_error() {
124     ///         Err(e) => {
125     ///             println!("Error: {}", e.description());
126     ///             println!("Caused by: {}", e.cause().unwrap());
127     ///         }
128     ///         _ => println!("No error"),
129     ///     }
130     /// }
131     /// ```
132     #[stable(feature = "rust1", since = "1.0.0")]
133     #[rustc_deprecated(since = "1.33.0", reason = "replaced by Error::source, which can support \
134                                                    downcasting")]
135     fn cause(&self) -> Option<&dyn Error> {
136         self.source()
137     }
138
139     /// The lower-level source of this error, if any.
140     ///
141     /// # Examples
142     ///
143     /// ```
144     /// use std::error::Error;
145     /// use std::fmt;
146     ///
147     /// #[derive(Debug)]
148     /// struct SuperError {
149     ///     side: SuperErrorSideKick,
150     /// }
151     ///
152     /// impl fmt::Display for SuperError {
153     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154     ///         write!(f, "SuperError is here!")
155     ///     }
156     /// }
157     ///
158     /// impl Error for SuperError {
159     ///     fn description(&self) -> &str {
160     ///         "I'm the superhero of errors"
161     ///     }
162     ///
163     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
164     ///         Some(&self.side)
165     ///     }
166     /// }
167     ///
168     /// #[derive(Debug)]
169     /// struct SuperErrorSideKick;
170     ///
171     /// impl fmt::Display for SuperErrorSideKick {
172     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173     ///         write!(f, "SuperErrorSideKick is here!")
174     ///     }
175     /// }
176     ///
177     /// impl Error for SuperErrorSideKick {
178     ///     fn description(&self) -> &str {
179     ///         "I'm SuperError side kick"
180     ///     }
181     /// }
182     ///
183     /// fn get_super_error() -> Result<(), SuperError> {
184     ///     Err(SuperError { side: SuperErrorSideKick })
185     /// }
186     ///
187     /// fn main() {
188     ///     match get_super_error() {
189     ///         Err(e) => {
190     ///             println!("Error: {}", e.description());
191     ///             println!("Caused by: {}", e.source().unwrap());
192     ///         }
193     ///         _ => println!("No error"),
194     ///     }
195     /// }
196     /// ```
197     #[stable(feature = "error_source", since = "1.30.0")]
198     fn source(&self) -> Option<&(dyn Error + 'static)> { None }
199
200     /// Gets the `TypeId` of `self`.
201     #[doc(hidden)]
202     #[unstable(feature = "error_type_id",
203                reason = "this is memory-unsafe to override in user code",
204                issue = "60784")]
205     fn type_id(&self, _: private::Internal) -> TypeId where Self: 'static {
206         TypeId::of::<Self>()
207     }
208
209     /// Returns a stack backtrace, if available, of where this error occurred.
210     ///
211     /// This function allows inspecting the location, in code, of where an error
212     /// happened. The returned `Backtrace` contains information about the stack
213     /// trace of the OS thread of execution of where the error originated from.
214     ///
215     /// Note that not all errors contain a `Backtrace`. Also note that a
216     /// `Backtrace` may actually be empty. For more information consult the
217     /// `Backtrace` type itself.
218     #[unstable(feature = "backtrace", issue = "53487")]
219     fn backtrace(&self) -> Option<&Backtrace> {
220         None
221     }
222 }
223
224 mod private {
225     // This is a hack to prevent `type_id` from being overridden by `Error`
226     // implementations, since that can enable unsound downcasting.
227     #[unstable(feature = "error_type_id", issue = "60784")]
228     #[derive(Debug)]
229     pub struct Internal;
230 }
231
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
234     /// Converts a type of [`Error`] into a box of dyn [`Error`].
235     ///
236     /// [`Error`]: ../error/trait.Error.html
237     ///
238     /// # Examples
239     ///
240     /// ```
241     /// use std::error::Error;
242     /// use std::fmt;
243     /// use std::mem;
244     ///
245     /// #[derive(Debug)]
246     /// struct AnError;
247     ///
248     /// impl fmt::Display for AnError {
249     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250     ///         write!(f , "An error")
251     ///     }
252     /// }
253     ///
254     /// impl Error for AnError {
255     ///     fn description(&self) -> &str {
256     ///         "Description of an error"
257     ///     }
258     /// }
259     ///
260     /// let an_error = AnError;
261     /// assert!(0 == mem::size_of_val(&an_error));
262     /// let a_boxed_error = Box::<dyn Error>::from(an_error);
263     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
264     /// ```
265     fn from(err: E) -> Box<dyn Error + 'a> {
266         Box::new(err)
267     }
268 }
269
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
272     /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
273     /// dyn [`Error`] + [`Send`] + [`Sync`].
274     ///
275     /// [`Error`]: ../error/trait.Error.html
276     ///
277     /// # Examples
278     ///
279     /// ```
280     /// use std::error::Error;
281     /// use std::fmt;
282     /// use std::mem;
283     ///
284     /// #[derive(Debug)]
285     /// struct AnError;
286     ///
287     /// impl fmt::Display for AnError {
288     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289     ///         write!(f , "An error")
290     ///     }
291     /// }
292     ///
293     /// impl Error for AnError {
294     ///     fn description(&self) -> &str {
295     ///         "Description of an error"
296     ///     }
297     /// }
298     ///
299     /// unsafe impl Send for AnError {}
300     ///
301     /// unsafe impl Sync for AnError {}
302     ///
303     /// let an_error = AnError;
304     /// assert!(0 == mem::size_of_val(&an_error));
305     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
306     /// assert!(
307     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
308     /// ```
309     fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
310         Box::new(err)
311     }
312 }
313
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl From<String> for Box<dyn Error + Send + Sync> {
316     /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
317     ///
318     /// [`Error`]: ../error/trait.Error.html
319     ///
320     /// # Examples
321     ///
322     /// ```
323     /// use std::error::Error;
324     /// use std::mem;
325     ///
326     /// let a_string_error = "a string error".to_string();
327     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
328     /// assert!(
329     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
330     /// ```
331     fn from(err: String) -> Box<dyn Error + Send + Sync> {
332         struct StringError(String);
333
334         impl Error for StringError {
335             fn description(&self) -> &str { &self.0 }
336         }
337
338         impl Display for StringError {
339             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340                 Display::fmt(&self.0, f)
341             }
342         }
343
344         // Purposefully skip printing "StringError(..)"
345         impl Debug for StringError {
346             fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347                 Debug::fmt(&self.0, f)
348             }
349         }
350
351         Box::new(StringError(err))
352     }
353 }
354
355 #[stable(feature = "string_box_error", since = "1.6.0")]
356 impl From<String> for Box<dyn Error> {
357     /// Converts a [`String`] into a box of dyn [`Error`].
358     ///
359     /// [`Error`]: ../error/trait.Error.html
360     ///
361     /// # Examples
362     ///
363     /// ```
364     /// use std::error::Error;
365     /// use std::mem;
366     ///
367     /// let a_string_error = "a string error".to_string();
368     /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
369     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
370     /// ```
371     fn from(str_err: String) -> Box<dyn Error> {
372         let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
373         let err2: Box<dyn Error> = err1;
374         err2
375     }
376 }
377
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
380     /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
381     ///
382     /// [`Error`]: ../error/trait.Error.html
383     ///
384     /// # Examples
385     ///
386     /// ```
387     /// use std::error::Error;
388     /// use std::mem;
389     ///
390     /// let a_str_error = "a str error";
391     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
392     /// assert!(
393     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
394     /// ```
395     fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
396         From::from(String::from(err))
397     }
398 }
399
400 #[stable(feature = "string_box_error", since = "1.6.0")]
401 impl From<&str> for Box<dyn Error> {
402     /// Converts a [`str`] into a box of dyn [`Error`].
403     ///
404     /// [`Error`]: ../error/trait.Error.html
405     ///
406     /// # Examples
407     ///
408     /// ```
409     /// use std::error::Error;
410     /// use std::mem;
411     ///
412     /// let a_str_error = "a str error";
413     /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
414     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
415     /// ```
416     fn from(err: &str) -> Box<dyn Error> {
417         From::from(String::from(err))
418     }
419 }
420
421 #[stable(feature = "cow_box_error", since = "1.22.0")]
422 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
423     /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
424     ///
425     /// [`Cow`]: ../borrow/enum.Cow.html
426     /// [`Error`]: ../error/trait.Error.html
427     ///
428     /// # Examples
429     ///
430     /// ```
431     /// use std::error::Error;
432     /// use std::mem;
433     /// use std::borrow::Cow;
434     ///
435     /// let a_cow_str_error = Cow::from("a str error");
436     /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
437     /// assert!(
438     ///     mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
439     /// ```
440     fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
441         From::from(String::from(err))
442     }
443 }
444
445 #[stable(feature = "cow_box_error", since = "1.22.0")]
446 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
447     /// Converts a [`Cow`] into a box of dyn [`Error`].
448     ///
449     /// [`Cow`]: ../borrow/enum.Cow.html
450     /// [`Error`]: ../error/trait.Error.html
451     ///
452     /// # Examples
453     ///
454     /// ```
455     /// use std::error::Error;
456     /// use std::mem;
457     /// use std::borrow::Cow;
458     ///
459     /// let a_cow_str_error = Cow::from("a str error");
460     /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
461     /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
462     /// ```
463     fn from(err: Cow<'a, str>) -> Box<dyn Error> {
464         From::from(String::from(err))
465     }
466 }
467
468 #[unstable(feature = "never_type", issue = "35121")]
469 impl Error for ! {
470     fn description(&self) -> &str { *self }
471 }
472
473 #[unstable(feature = "allocator_api",
474            reason = "the precise API and guarantees it provides may be tweaked.",
475            issue = "32838")]
476 impl Error for AllocErr {
477     fn description(&self) -> &str {
478         "memory allocation failed"
479     }
480 }
481
482 #[unstable(feature = "allocator_api",
483            reason = "the precise API and guarantees it provides may be tweaked.",
484            issue = "32838")]
485 impl Error for LayoutErr {
486     fn description(&self) -> &str {
487         "invalid parameters to Layout::from_size_align"
488     }
489 }
490
491 #[unstable(feature = "allocator_api",
492            reason = "the precise API and guarantees it provides may be tweaked.",
493            issue = "32838")]
494 impl Error for CannotReallocInPlace {
495     fn description(&self) -> &str {
496         CannotReallocInPlace::description(self)
497     }
498 }
499
500 #[stable(feature = "rust1", since = "1.0.0")]
501 impl Error for str::ParseBoolError {
502     fn description(&self) -> &str { "failed to parse bool" }
503 }
504
505 #[stable(feature = "rust1", since = "1.0.0")]
506 impl Error for str::Utf8Error {
507     fn description(&self) -> &str {
508         "invalid utf-8: corrupt contents"
509     }
510 }
511
512 #[stable(feature = "rust1", since = "1.0.0")]
513 impl Error for num::ParseIntError {
514     fn description(&self) -> &str {
515         self.__description()
516     }
517 }
518
519 #[stable(feature = "try_from", since = "1.34.0")]
520 impl Error for num::TryFromIntError {
521     fn description(&self) -> &str {
522         self.__description()
523     }
524 }
525
526 #[stable(feature = "try_from", since = "1.34.0")]
527 impl Error for array::TryFromSliceError {
528     fn description(&self) -> &str {
529         self.__description()
530     }
531 }
532
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl Error for num::ParseFloatError {
535     fn description(&self) -> &str {
536         self.__description()
537     }
538 }
539
540 #[stable(feature = "rust1", since = "1.0.0")]
541 impl Error for string::FromUtf8Error {
542     fn description(&self) -> &str {
543         "invalid utf-8"
544     }
545 }
546
547 #[stable(feature = "rust1", since = "1.0.0")]
548 impl Error for string::FromUtf16Error {
549     fn description(&self) -> &str {
550         "invalid utf-16"
551     }
552 }
553
554 #[stable(feature = "str_parse_error2", since = "1.8.0")]
555 impl Error for string::ParseError {
556     fn description(&self) -> &str {
557         match *self {}
558     }
559 }
560
561 #[stable(feature = "decode_utf16", since = "1.9.0")]
562 impl Error for char::DecodeUtf16Error {
563     fn description(&self) -> &str {
564         "unpaired surrogate found"
565     }
566 }
567
568 #[stable(feature = "box_error", since = "1.8.0")]
569 impl<T: Error> Error for Box<T> {
570     fn description(&self) -> &str {
571         Error::description(&**self)
572     }
573
574     #[allow(deprecated)]
575     fn cause(&self) -> Option<&dyn Error> {
576         Error::cause(&**self)
577     }
578
579     fn source(&self) -> Option<&(dyn Error + 'static)> {
580         Error::source(&**self)
581     }
582 }
583
584 #[stable(feature = "fmt_error", since = "1.11.0")]
585 impl Error for fmt::Error {
586     fn description(&self) -> &str {
587         "an error occurred when formatting an argument"
588     }
589 }
590
591 #[stable(feature = "try_borrow", since = "1.13.0")]
592 impl Error for cell::BorrowError {
593     fn description(&self) -> &str {
594         "already mutably borrowed"
595     }
596 }
597
598 #[stable(feature = "try_borrow", since = "1.13.0")]
599 impl Error for cell::BorrowMutError {
600     fn description(&self) -> &str {
601         "already borrowed"
602     }
603 }
604
605 #[stable(feature = "try_from", since = "1.34.0")]
606 impl Error for char::CharTryFromError {
607     fn description(&self) -> &str {
608         "converted integer out of range for `char`"
609     }
610 }
611
612 #[stable(feature = "char_from_str", since = "1.20.0")]
613 impl Error for char::ParseCharError {
614     fn description(&self) -> &str {
615         self.__description()
616     }
617 }
618
619 // Copied from `any.rs`.
620 impl dyn Error + 'static {
621     /// Returns `true` if the boxed type is the same as `T`
622     #[stable(feature = "error_downcast", since = "1.3.0")]
623     #[inline]
624     pub fn is<T: Error + 'static>(&self) -> bool {
625         // Get `TypeId` of the type this function is instantiated with.
626         let t = TypeId::of::<T>();
627
628         // Get `TypeId` of the type in the trait object.
629         let boxed = self.type_id(private::Internal);
630
631         // Compare both `TypeId`s on equality.
632         t == boxed
633     }
634
635     /// Returns some reference to the boxed value if it is of type `T`, or
636     /// `None` if it isn't.
637     #[stable(feature = "error_downcast", since = "1.3.0")]
638     #[inline]
639     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
640         if self.is::<T>() {
641             unsafe {
642                 Some(&*(self as *const dyn Error as *const T))
643             }
644         } else {
645             None
646         }
647     }
648
649     /// Returns some mutable reference to the boxed value if it is of type `T`, or
650     /// `None` if it isn't.
651     #[stable(feature = "error_downcast", since = "1.3.0")]
652     #[inline]
653     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
654         if self.is::<T>() {
655             unsafe {
656                 Some(&mut *(self as *mut dyn Error as *mut T))
657             }
658         } else {
659             None
660         }
661     }
662 }
663
664 impl dyn Error + 'static + Send {
665     /// Forwards to the method defined on the type `dyn Error`.
666     #[stable(feature = "error_downcast", since = "1.3.0")]
667     #[inline]
668     pub fn is<T: Error + 'static>(&self) -> bool {
669         <dyn Error + 'static>::is::<T>(self)
670     }
671
672     /// Forwards to the method defined on the type `dyn Error`.
673     #[stable(feature = "error_downcast", since = "1.3.0")]
674     #[inline]
675     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
676         <dyn Error + 'static>::downcast_ref::<T>(self)
677     }
678
679     /// Forwards to the method defined on the type `dyn Error`.
680     #[stable(feature = "error_downcast", since = "1.3.0")]
681     #[inline]
682     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
683         <dyn Error + 'static>::downcast_mut::<T>(self)
684     }
685 }
686
687 impl dyn Error + 'static + Send + Sync {
688     /// Forwards to the method defined on the type `dyn Error`.
689     #[stable(feature = "error_downcast", since = "1.3.0")]
690     #[inline]
691     pub fn is<T: Error + 'static>(&self) -> bool {
692         <dyn Error + 'static>::is::<T>(self)
693     }
694
695     /// Forwards to the method defined on the type `dyn Error`.
696     #[stable(feature = "error_downcast", since = "1.3.0")]
697     #[inline]
698     pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
699         <dyn Error + 'static>::downcast_ref::<T>(self)
700     }
701
702     /// Forwards to the method defined on the type `dyn Error`.
703     #[stable(feature = "error_downcast", since = "1.3.0")]
704     #[inline]
705     pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
706         <dyn Error + 'static>::downcast_mut::<T>(self)
707     }
708 }
709
710 impl dyn Error {
711     #[inline]
712     #[stable(feature = "error_downcast", since = "1.3.0")]
713     /// Attempts to downcast the box to a concrete type.
714     pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
715         if self.is::<T>() {
716             unsafe {
717                 let raw: *mut dyn Error = Box::into_raw(self);
718                 Ok(Box::from_raw(raw as *mut T))
719             }
720         } else {
721             Err(self)
722         }
723     }
724
725     /// Returns an iterator starting with the current error and continuing with
726     /// recursively calling [`source`].
727     ///
728     /// If you want to omit the current error and only use its sources,
729     /// use `skip(1)`.
730     ///
731     /// # Examples
732     ///
733     /// ```
734     /// #![feature(error_iter)]
735     /// use std::error::Error;
736     /// use std::fmt;
737     ///
738     /// #[derive(Debug)]
739     /// struct A;
740     ///
741     /// #[derive(Debug)]
742     /// struct B(Option<Box<dyn Error + 'static>>);
743     ///
744     /// impl fmt::Display for A {
745     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
746     ///         write!(f, "A")
747     ///     }
748     /// }
749     ///
750     /// impl fmt::Display for B {
751     ///     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752     ///         write!(f, "B")
753     ///     }
754     /// }
755     ///
756     /// impl Error for A {}
757     ///
758     /// impl Error for B {
759     ///     fn source(&self) -> Option<&(dyn Error + 'static)> {
760     ///         self.0.as_ref().map(|e| e.as_ref())
761     ///     }
762     /// }
763     ///
764     /// let b = B(Some(Box::new(A)));
765     ///
766     /// // let err : Box<Error> = b.into(); // or
767     /// let err = &b as &(dyn Error);
768     ///
769     /// let mut iter = err.chain();
770     ///
771     /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
772     /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
773     /// assert!(iter.next().is_none());
774     /// assert!(iter.next().is_none());
775     /// ```
776     ///
777     /// [`source`]: trait.Error.html#method.source
778     #[unstable(feature = "error_iter", issue = "58520")]
779     #[inline]
780     pub fn chain(&self) -> Chain<'_> {
781         Chain {
782             current: Some(self),
783         }
784     }
785 }
786
787 /// An iterator over an [`Error`] and its sources.
788 ///
789 /// If you want to omit the initial error and only process
790 /// its sources, use `skip(1)`.
791 ///
792 /// [`Error`]: trait.Error.html
793 #[unstable(feature = "error_iter", issue = "58520")]
794 #[derive(Clone, Debug)]
795 pub struct Chain<'a> {
796     current: Option<&'a (dyn Error + 'static)>,
797 }
798
799 #[unstable(feature = "error_iter", issue = "58520")]
800 impl<'a> Iterator for Chain<'a> {
801     type Item = &'a (dyn Error + 'static);
802
803     fn next(&mut self) -> Option<Self::Item> {
804         let current = self.current;
805         self.current = self.current.and_then(Error::source);
806         current
807     }
808 }
809
810 impl dyn Error + Send {
811     #[inline]
812     #[stable(feature = "error_downcast", since = "1.3.0")]
813     /// Attempts to downcast the box to a concrete type.
814     pub fn downcast<T: Error + 'static>(self: Box<Self>)
815                                         -> Result<Box<T>, Box<dyn Error + Send>> {
816         let err: Box<dyn Error> = self;
817         <dyn Error>::downcast(err).map_err(|s| unsafe {
818             // Reapply the `Send` marker.
819             transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
820         })
821     }
822 }
823
824 impl dyn Error + Send + Sync {
825     #[inline]
826     #[stable(feature = "error_downcast", since = "1.3.0")]
827     /// Attempts to downcast the box to a concrete type.
828     pub fn downcast<T: Error + 'static>(self: Box<Self>)
829                                         -> Result<Box<T>, Box<Self>> {
830         let err: Box<dyn Error> = self;
831         <dyn Error>::downcast(err).map_err(|s| unsafe {
832             // Reapply the `Send + Sync` marker.
833             transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
834         })
835     }
836 }
837
838 #[cfg(test)]
839 mod tests {
840     use super::Error;
841     use crate::fmt;
842
843     #[derive(Debug, PartialEq)]
844     struct A;
845     #[derive(Debug, PartialEq)]
846     struct B;
847
848     impl fmt::Display for A {
849         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
850             write!(f, "A")
851         }
852     }
853     impl fmt::Display for B {
854         fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
855             write!(f, "B")
856         }
857     }
858
859     impl Error for A {
860         fn description(&self) -> &str { "A-desc" }
861     }
862     impl Error for B {
863         fn description(&self) -> &str { "A-desc" }
864     }
865
866     #[test]
867     fn downcasting() {
868         let mut a = A;
869         let a = &mut a as &mut (dyn Error + 'static);
870         assert_eq!(a.downcast_ref::<A>(), Some(&A));
871         assert_eq!(a.downcast_ref::<B>(), None);
872         assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
873         assert_eq!(a.downcast_mut::<B>(), None);
874
875         let a: Box<dyn Error> = Box::new(A);
876         match a.downcast::<B>() {
877             Ok(..) => panic!("expected error"),
878             Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),
879         }
880     }
881 }