]> git.proxmox.com Git - rustc.git/blob - library/std/src/error.rs
New upstream version 1.55.0+dfsg1
[rustc.git] / library / std / src / 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 #[cfg(test)]
17 mod tests;
18
19 use core::array;
20 use core::convert::Infallible;
21
22 use crate::alloc::{AllocError, LayoutError};
23 use crate::any::TypeId;
24 use crate::backtrace::Backtrace;
25 use crate::borrow::Cow;
26 use crate::cell;
27 use crate::char;
28 use crate::fmt::{self, Debug, Display};
29 use crate::mem::transmute;
30 use crate::num;
31 use crate::str;
32 use crate::string;
33 use crate::sync::Arc;
34
35 /// `Error` is a trait representing the basic expectations for error values,
36 /// i.e., values of type `E` in [`Result<T, E>`].
37 ///
38 /// Errors must describe themselves through the [`Display`] and [`Debug`]
39 /// traits. Error messages are typically concise lowercase sentences without
40 /// trailing punctuation:
41 ///
42 /// ```
43 /// let err = "NaN".parse::<u32>().unwrap_err();
44 /// assert_eq!(err.to_string(), "invalid digit found in string");
45 /// ```
46 ///
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.
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// use std::error::Error;
61 /// use std::fmt;
62 ///
63 /// #[derive(Debug)]
64 /// struct SuperError {
65 /// side: SuperErrorSideKick,
66 /// }
67 ///
68 /// impl fmt::Display for SuperError {
69 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 /// write!(f, "SuperError is here!")
71 /// }
72 /// }
73 ///
74 /// impl Error for SuperError {
75 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
76 /// Some(&self.side)
77 /// }
78 /// }
79 ///
80 /// #[derive(Debug)]
81 /// struct SuperErrorSideKick;
82 ///
83 /// impl fmt::Display for SuperErrorSideKick {
84 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85 /// write!(f, "SuperErrorSideKick is here!")
86 /// }
87 /// }
88 ///
89 /// impl Error for SuperErrorSideKick {}
90 ///
91 /// fn get_super_error() -> Result<(), SuperError> {
92 /// Err(SuperError { side: SuperErrorSideKick })
93 /// }
94 ///
95 /// fn main() {
96 /// match get_super_error() {
97 /// Err(e) => {
98 /// println!("Error: {}", e);
99 /// println!("Caused by: {}", e.source().unwrap());
100 /// }
101 /// _ => println!("No error"),
102 /// }
103 /// }
104 /// ```
105 #[stable(feature = "error_source", since = "1.30.0")]
106 fn source(&self) -> Option<&(dyn Error + 'static)> {
107 None
108 }
109
110 /// Gets the `TypeId` of `self`.
111 #[doc(hidden)]
112 #[unstable(
113 feature = "error_type_id",
114 reason = "this is memory-unsafe to override in user code",
115 issue = "60784"
116 )]
117 fn type_id(&self, _: private::Internal) -> TypeId
118 where
119 Self: 'static,
120 {
121 TypeId::of::<Self>()
122 }
123
124 /// Returns a stack backtrace, if available, of where this error occurred.
125 ///
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.
129 ///
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> {
135 None
136 }
137
138 /// ```
139 /// if let Err(e) = "xc".parse::<u32>() {
140 /// // Print `e` itself, no need for description().
141 /// eprintln!("Error: {}", e);
142 /// }
143 /// ```
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"
148 }
149
150 #[stable(feature = "rust1", since = "1.0.0")]
151 #[rustc_deprecated(
152 since = "1.33.0",
153 reason = "replaced by Error::source, which can support downcasting"
154 )]
155 #[allow(missing_docs)]
156 fn cause(&self) -> Option<&dyn Error> {
157 self.source()
158 }
159 }
160
161 mod private {
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")]
165 #[derive(Debug)]
166 pub struct Internal;
167 }
168
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`].
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use std::error::Error;
177 /// use std::fmt;
178 /// use std::mem;
179 ///
180 /// #[derive(Debug)]
181 /// struct AnError;
182 ///
183 /// impl fmt::Display for AnError {
184 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 /// write!(f , "An error")
186 /// }
187 /// }
188 ///
189 /// impl Error for AnError {}
190 ///
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))
195 /// ```
196 fn from(err: E) -> Box<dyn Error + 'a> {
197 Box::new(err)
198 }
199 }
200
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`].
205 ///
206 /// # Examples
207 ///
208 /// ```
209 /// use std::error::Error;
210 /// use std::fmt;
211 /// use std::mem;
212 ///
213 /// #[derive(Debug)]
214 /// struct AnError;
215 ///
216 /// impl fmt::Display for AnError {
217 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 /// write!(f , "An error")
219 /// }
220 /// }
221 ///
222 /// impl Error for AnError {}
223 ///
224 /// unsafe impl Send for AnError {}
225 ///
226 /// unsafe impl Sync for AnError {}
227 ///
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);
231 /// assert!(
232 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
233 /// ```
234 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
235 Box::new(err)
236 }
237 }
238
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`].
242 ///
243 /// # Examples
244 ///
245 /// ```
246 /// use std::error::Error;
247 /// use std::mem;
248 ///
249 /// let a_string_error = "a string error".to_string();
250 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
251 /// assert!(
252 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
253 /// ```
254 #[inline]
255 fn from(err: String) -> Box<dyn Error + Send + Sync> {
256 struct StringError(String);
257
258 impl Error for StringError {
259 #[allow(deprecated)]
260 fn description(&self) -> &str {
261 &self.0
262 }
263 }
264
265 impl Display for StringError {
266 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267 Display::fmt(&self.0, f)
268 }
269 }
270
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)
275 }
276 }
277
278 Box::new(StringError(err))
279 }
280 }
281
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`].
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// use std::error::Error;
290 /// use std::mem;
291 ///
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))
295 /// ```
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;
299 err2
300 }
301 }
302
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`].
306 ///
307 /// [`str`]: prim@str
308 ///
309 /// # Examples
310 ///
311 /// ```
312 /// use std::error::Error;
313 /// use std::mem;
314 ///
315 /// let a_str_error = "a str error";
316 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
317 /// assert!(
318 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
319 /// ```
320 #[inline]
321 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
322 From::from(String::from(err))
323 }
324 }
325
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`].
329 ///
330 /// [`str`]: prim@str
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// use std::error::Error;
336 /// use std::mem;
337 ///
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))
341 /// ```
342 fn from(err: &str) -> Box<dyn Error> {
343 From::from(String::from(err))
344 }
345 }
346
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`].
350 ///
351 /// # Examples
352 ///
353 /// ```
354 /// use std::error::Error;
355 /// use std::mem;
356 /// use std::borrow::Cow;
357 ///
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);
360 /// assert!(
361 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
362 /// ```
363 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
364 From::from(String::from(err))
365 }
366 }
367
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`].
371 ///
372 /// # Examples
373 ///
374 /// ```
375 /// use std::error::Error;
376 /// use std::mem;
377 /// use std::borrow::Cow;
378 ///
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))
382 /// ```
383 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
384 From::from(String::from(err))
385 }
386 }
387
388 #[unstable(feature = "never_type", issue = "35121")]
389 impl Error for ! {}
390
391 #[unstable(
392 feature = "allocator_api",
393 reason = "the precise API and guarantees it provides may be tweaked.",
394 issue = "32838"
395 )]
396 impl Error for AllocError {}
397
398 #[stable(feature = "alloc_layout", since = "1.28.0")]
399 impl Error for LayoutError {}
400
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl Error for str::ParseBoolError {
403 #[allow(deprecated)]
404 fn description(&self) -> &str {
405 "failed to parse bool"
406 }
407 }
408
409 #[stable(feature = "rust1", since = "1.0.0")]
410 impl Error for str::Utf8Error {
411 #[allow(deprecated)]
412 fn description(&self) -> &str {
413 "invalid utf-8: corrupt contents"
414 }
415 }
416
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl Error for num::ParseIntError {
419 #[allow(deprecated)]
420 fn description(&self) -> &str {
421 self.__description()
422 }
423 }
424
425 #[stable(feature = "try_from", since = "1.34.0")]
426 impl Error for num::TryFromIntError {
427 #[allow(deprecated)]
428 fn description(&self) -> &str {
429 self.__description()
430 }
431 }
432
433 #[stable(feature = "try_from", since = "1.34.0")]
434 impl Error for array::TryFromSliceError {
435 #[allow(deprecated)]
436 fn description(&self) -> &str {
437 self.__description()
438 }
439 }
440
441 #[stable(feature = "rust1", since = "1.0.0")]
442 impl Error for num::ParseFloatError {
443 #[allow(deprecated)]
444 fn description(&self) -> &str {
445 self.__description()
446 }
447 }
448
449 #[stable(feature = "rust1", since = "1.0.0")]
450 impl Error for string::FromUtf8Error {
451 #[allow(deprecated)]
452 fn description(&self) -> &str {
453 "invalid utf-8"
454 }
455 }
456
457 #[stable(feature = "rust1", since = "1.0.0")]
458 impl Error for string::FromUtf16Error {
459 #[allow(deprecated)]
460 fn description(&self) -> &str {
461 "invalid utf-16"
462 }
463 }
464
465 #[stable(feature = "str_parse_error2", since = "1.8.0")]
466 impl Error for Infallible {
467 fn description(&self) -> &str {
468 match *self {}
469 }
470 }
471
472 #[stable(feature = "decode_utf16", since = "1.9.0")]
473 impl Error for char::DecodeUtf16Error {
474 #[allow(deprecated)]
475 fn description(&self) -> &str {
476 "unpaired surrogate found"
477 }
478 }
479
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>
483 {
484 #[allow(deprecated)]
485 fn description(&self) -> &str {
486 "key already exists"
487 }
488 }
489
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> {
492 #[allow(deprecated)]
493 fn description(&self) -> &str {
494 "key already exists"
495 }
496 }
497
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)
503 }
504
505 #[allow(deprecated)]
506 fn cause(&self) -> Option<&dyn Error> {
507 Error::cause(&**self)
508 }
509
510 fn source(&self) -> Option<&(dyn Error + 'static)> {
511 Error::source(&**self)
512 }
513 }
514
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)
520 }
521
522 #[allow(deprecated)]
523 fn cause(&self) -> Option<&dyn Error> {
524 Error::cause(&**self)
525 }
526
527 fn source(&self) -> Option<&(dyn Error + 'static)> {
528 Error::source(&**self)
529 }
530
531 fn backtrace(&self) -> Option<&Backtrace> {
532 Error::backtrace(&**self)
533 }
534 }
535
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)
541 }
542
543 #[allow(deprecated)]
544 fn cause(&self) -> Option<&dyn Error> {
545 Error::cause(&**self)
546 }
547
548 fn source(&self) -> Option<&(dyn Error + 'static)> {
549 Error::source(&**self)
550 }
551
552 fn backtrace(&self) -> Option<&Backtrace> {
553 Error::backtrace(&**self)
554 }
555 }
556
557 #[stable(feature = "fmt_error", since = "1.11.0")]
558 impl Error for fmt::Error {
559 #[allow(deprecated)]
560 fn description(&self) -> &str {
561 "an error occurred when formatting an argument"
562 }
563 }
564
565 #[stable(feature = "try_borrow", since = "1.13.0")]
566 impl Error for cell::BorrowError {
567 #[allow(deprecated)]
568 fn description(&self) -> &str {
569 "already mutably borrowed"
570 }
571 }
572
573 #[stable(feature = "try_borrow", since = "1.13.0")]
574 impl Error for cell::BorrowMutError {
575 #[allow(deprecated)]
576 fn description(&self) -> &str {
577 "already borrowed"
578 }
579 }
580
581 #[stable(feature = "try_from", since = "1.34.0")]
582 impl Error for char::CharTryFromError {
583 #[allow(deprecated)]
584 fn description(&self) -> &str {
585 "converted integer out of range for `char`"
586 }
587 }
588
589 #[stable(feature = "char_from_str", since = "1.20.0")]
590 impl Error for char::ParseCharError {
591 #[allow(deprecated)]
592 fn description(&self) -> &str {
593 self.__description()
594 }
595 }
596
597 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
598 impl Error for alloc::collections::TryReserveError {}
599
600 #[unstable(feature = "duration_checked_float", issue = "83400")]
601 impl Error for core::time::FromSecsError {}
602
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")]
607 #[inline]
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>();
611
612 // Get `TypeId` of the type in the trait object.
613 let boxed = self.type_id(private::Internal);
614
615 // Compare both `TypeId`s on equality.
616 t == boxed
617 }
618
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")]
622 #[inline]
623 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
624 if self.is::<T>() {
625 unsafe { Some(&*(self as *const dyn Error as *const T)) }
626 } else {
627 None
628 }
629 }
630
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")]
634 #[inline]
635 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
636 if self.is::<T>() {
637 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
638 } else {
639 None
640 }
641 }
642 }
643
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")]
647 #[inline]
648 pub fn is<T: Error + 'static>(&self) -> bool {
649 <dyn Error + 'static>::is::<T>(self)
650 }
651
652 /// Forwards to the method defined on the type `dyn Error`.
653 #[stable(feature = "error_downcast", since = "1.3.0")]
654 #[inline]
655 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
656 <dyn Error + 'static>::downcast_ref::<T>(self)
657 }
658
659 /// Forwards to the method defined on the type `dyn Error`.
660 #[stable(feature = "error_downcast", since = "1.3.0")]
661 #[inline]
662 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
663 <dyn Error + 'static>::downcast_mut::<T>(self)
664 }
665 }
666
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")]
670 #[inline]
671 pub fn is<T: Error + 'static>(&self) -> bool {
672 <dyn Error + 'static>::is::<T>(self)
673 }
674
675 /// Forwards to the method defined on the type `dyn Error`.
676 #[stable(feature = "error_downcast", since = "1.3.0")]
677 #[inline]
678 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
679 <dyn Error + 'static>::downcast_ref::<T>(self)
680 }
681
682 /// Forwards to the method defined on the type `dyn Error`.
683 #[stable(feature = "error_downcast", since = "1.3.0")]
684 #[inline]
685 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
686 <dyn Error + 'static>::downcast_mut::<T>(self)
687 }
688 }
689
690 impl dyn Error {
691 #[inline]
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>> {
695 if self.is::<T>() {
696 unsafe {
697 let raw: *mut dyn Error = Box::into_raw(self);
698 Ok(Box::from_raw(raw as *mut T))
699 }
700 } else {
701 Err(self)
702 }
703 }
704
705 /// Returns an iterator starting with the current error and continuing with
706 /// recursively calling [`Error::source`].
707 ///
708 /// If you want to omit the current error and only use its sources,
709 /// use `skip(1)`.
710 ///
711 /// # Examples
712 ///
713 /// ```
714 /// #![feature(error_iter)]
715 /// use std::error::Error;
716 /// use std::fmt;
717 ///
718 /// #[derive(Debug)]
719 /// struct A;
720 ///
721 /// #[derive(Debug)]
722 /// struct B(Option<Box<dyn Error + 'static>>);
723 ///
724 /// impl fmt::Display for A {
725 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726 /// write!(f, "A")
727 /// }
728 /// }
729 ///
730 /// impl fmt::Display for B {
731 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
732 /// write!(f, "B")
733 /// }
734 /// }
735 ///
736 /// impl Error for A {}
737 ///
738 /// impl Error for B {
739 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
740 /// self.0.as_ref().map(|e| e.as_ref())
741 /// }
742 /// }
743 ///
744 /// let b = B(Some(Box::new(A)));
745 ///
746 /// // let err : Box<Error> = b.into(); // or
747 /// let err = &b as &(dyn Error);
748 ///
749 /// let mut iter = err.chain();
750 ///
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());
755 /// ```
756 #[unstable(feature = "error_iter", issue = "58520")]
757 #[inline]
758 pub fn chain(&self) -> Chain<'_> {
759 Chain { current: Some(self) }
760 }
761 }
762
763 /// An iterator over an [`Error`] and its sources.
764 ///
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)>,
771 }
772
773 #[unstable(feature = "error_iter", issue = "58520")]
774 impl<'a> Iterator for Chain<'a> {
775 type Item = &'a (dyn Error + 'static);
776
777 fn next(&mut self) -> Option<Self::Item> {
778 let current = self.current;
779 self.current = self.current.and_then(Error::source);
780 current
781 }
782 }
783
784 impl dyn Error + Send {
785 #[inline]
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)
793 })
794 }
795 }
796
797 impl dyn Error + Send + Sync {
798 #[inline]
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)
806 })
807 }
808 }