1 #![doc = include_str!("error.md")]
2 #![unstable(feature = "error_in_core", issue = "none")]
4 // A note about crates and the facade:
6 // Originally, the `Error` trait was defined in libcore, and the impls
7 // were scattered about. However, coherence objected to this
8 // arrangement, because to create the blanket impls for `Box` required
9 // knowing that `&str: !Error`, and we have no means to deal with that
10 // sort of conflict just now. Therefore, for the time being, we have
11 // moved the `Error` trait into libstd. As we evolve a sol'n to the
12 // coherence challenge (e.g., specialization, neg impls, etc) we can
13 // reconsider what crate these items belong in.
18 use crate::any::{Demand, Provider, TypeId};
19 use crate::fmt::{Debug, Display};
21 /// `Error` is a trait representing the basic expectations for error values,
22 /// i.e., values of type `E` in [`Result<T, E>`].
24 /// Errors must describe themselves through the [`Display`] and [`Debug`]
25 /// traits. Error messages are typically concise lowercase sentences without
26 /// trailing punctuation:
29 /// let err = "NaN".parse::<u32>().unwrap_err();
30 /// assert_eq!(err.to_string(), "invalid digit found in string");
33 /// Errors may provide cause chain information. [`Error::source()`] is generally
34 /// used when errors cross "abstraction boundaries". If one module must report
35 /// an error that is caused by an error from a lower-level module, it can allow
36 /// accessing that error via [`Error::source()`]. This makes it possible for the
37 /// high-level module to provide its own errors while also revealing some of the
38 /// implementation for debugging via `source` chains.
39 #[stable(feature = "rust1", since = "1.0.0")]
40 #[cfg_attr(not(test), rustc_diagnostic_item = "Error")]
41 #[rustc_has_incoherent_inherent_impls]
42 pub trait Error: Debug + Display {
43 /// The lower-level source of this error, if any.
48 /// use std::error::Error;
52 /// struct SuperError {
53 /// source: SuperErrorSideKick,
56 /// impl fmt::Display for SuperError {
57 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 /// write!(f, "SuperError is here!")
62 /// impl Error for SuperError {
63 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
64 /// Some(&self.source)
69 /// struct SuperErrorSideKick;
71 /// impl fmt::Display for SuperErrorSideKick {
72 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 /// write!(f, "SuperErrorSideKick is here!")
77 /// impl Error for SuperErrorSideKick {}
79 /// fn get_super_error() -> Result<(), SuperError> {
80 /// Err(SuperError { source: SuperErrorSideKick })
84 /// match get_super_error() {
86 /// println!("Error: {e}");
87 /// println!("Caused by: {}", e.source().unwrap());
89 /// _ => println!("No error"),
93 #[stable(feature = "error_source", since = "1.30.0")]
94 fn source(&self) -> Option<&(dyn Error + 'static)> {
98 /// Gets the `TypeId` of `self`.
101 feature = "error_type_id",
102 reason = "this is memory-unsafe to override in user code",
105 fn type_id(&self, _: private::Internal) -> TypeId
113 /// if let Err(e) = "xc".parse::<u32>() {
114 /// // Print `e` itself, no need for description().
115 /// eprintln!("Error: {e}");
118 #[stable(feature = "rust1", since = "1.0.0")]
119 #[deprecated(since = "1.42.0", note = "use the Display impl or to_string()")]
120 fn description(&self) -> &str {
121 "description() is deprecated; use Display"
124 #[stable(feature = "rust1", since = "1.0.0")]
127 note = "replaced by Error::source, which can support downcasting"
129 #[allow(missing_docs)]
130 fn cause(&self) -> Option<&dyn Error> {
134 /// Provides type based access to context intended for error reports.
136 /// Used in conjunction with [`Demand::provide_value`] and [`Demand::provide_ref`] to extract
137 /// references to member variables from `dyn Error` trait objects.
142 /// #![feature(provide_any)]
143 /// #![feature(error_generic_member_access)]
145 /// use core::any::Demand;
148 /// struct MyBacktrace {
152 /// impl MyBacktrace {
153 /// fn new() -> MyBacktrace {
160 /// struct SourceError {
164 /// impl fmt::Display for SourceError {
165 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 /// write!(f, "Example Source Error")
170 /// impl std::error::Error for SourceError {}
174 /// source: SourceError,
175 /// backtrace: MyBacktrace,
178 /// impl fmt::Display for Error {
179 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 /// write!(f, "Example Error")
184 /// impl std::error::Error for Error {
185 /// fn provide<'a>(&'a self, req: &mut Demand<'a>) {
187 /// .provide_ref::<MyBacktrace>(&self.backtrace)
188 /// .provide_ref::<dyn std::error::Error + 'static>(&self.source);
193 /// let backtrace = MyBacktrace::new();
194 /// let source = SourceError {};
195 /// let error = Error { source, backtrace };
196 /// let dyn_error = &error as &dyn std::error::Error;
197 /// let backtrace_ref = dyn_error.request_ref::<MyBacktrace>().unwrap();
199 /// assert!(core::ptr::eq(&error.backtrace, backtrace_ref));
202 #[unstable(feature = "error_generic_member_access", issue = "99301")]
203 #[allow(unused_variables)]
204 fn provide<'a>(&'a self, req: &mut Demand<'a>) {}
207 #[unstable(feature = "error_generic_member_access", issue = "99301")]
208 impl<E> Provider for E
212 fn provide<'a>(&'a self, req: &mut Demand<'a>) {
218 // This is a hack to prevent `type_id` from being overridden by `Error`
219 // implementations, since that can enable unsound downcasting.
220 #[unstable(feature = "error_type_id", issue = "60784")]
225 #[unstable(feature = "never_type", issue = "35121")]
228 impl<'a> dyn Error + 'a {
229 /// Request a reference of type `T` as context about this error.
230 #[unstable(feature = "error_generic_member_access", issue = "99301")]
231 pub fn request_ref<T: ?Sized + 'static>(&'a self) -> Option<&'a T> {
232 core::any::request_ref(self)
235 /// Request a value of type `T` as context about this error.
236 #[unstable(feature = "error_generic_member_access", issue = "99301")]
237 pub fn request_value<T: 'static>(&'a self) -> Option<T> {
238 core::any::request_value(self)
242 // Copied from `any.rs`.
243 impl dyn Error + 'static {
244 /// Returns `true` if the inner type is the same as `T`.
245 #[stable(feature = "error_downcast", since = "1.3.0")]
247 pub fn is<T: Error + 'static>(&self) -> bool {
248 // Get `TypeId` of the type this function is instantiated with.
249 let t = TypeId::of::<T>();
251 // Get `TypeId` of the type in the trait object (`self`).
252 let concrete = self.type_id(private::Internal);
254 // Compare both `TypeId`s on equality.
258 /// Returns some reference to the inner value if it is of type `T`, or
259 /// `None` if it isn't.
260 #[stable(feature = "error_downcast", since = "1.3.0")]
262 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
264 // SAFETY: `is` ensures this type cast is correct
265 unsafe { Some(&*(self as *const dyn Error as *const T)) }
271 /// Returns some mutable reference to the inner value if it is of type `T`, or
272 /// `None` if it isn't.
273 #[stable(feature = "error_downcast", since = "1.3.0")]
275 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
277 // SAFETY: `is` ensures this type cast is correct
278 unsafe { Some(&mut *(self as *mut dyn Error as *mut T)) }
285 impl dyn Error + 'static + Send {
286 /// Forwards to the method defined on the type `dyn Error`.
287 #[stable(feature = "error_downcast", since = "1.3.0")]
289 pub fn is<T: Error + 'static>(&self) -> bool {
290 <dyn Error + 'static>::is::<T>(self)
293 /// Forwards to the method defined on the type `dyn Error`.
294 #[stable(feature = "error_downcast", since = "1.3.0")]
296 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
297 <dyn Error + 'static>::downcast_ref::<T>(self)
300 /// Forwards to the method defined on the type `dyn Error`.
301 #[stable(feature = "error_downcast", since = "1.3.0")]
303 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
304 <dyn Error + 'static>::downcast_mut::<T>(self)
307 /// Request a reference of type `T` as context about this error.
308 #[unstable(feature = "error_generic_member_access", issue = "99301")]
309 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
310 <dyn Error>::request_ref(self)
313 /// Request a value of type `T` as context about this error.
314 #[unstable(feature = "error_generic_member_access", issue = "99301")]
315 pub fn request_value<T: 'static>(&self) -> Option<T> {
316 <dyn Error>::request_value(self)
320 impl dyn Error + 'static + Send + Sync {
321 /// Forwards to the method defined on the type `dyn Error`.
322 #[stable(feature = "error_downcast", since = "1.3.0")]
324 pub fn is<T: Error + 'static>(&self) -> bool {
325 <dyn Error + 'static>::is::<T>(self)
328 /// Forwards to the method defined on the type `dyn Error`.
329 #[stable(feature = "error_downcast", since = "1.3.0")]
331 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
332 <dyn Error + 'static>::downcast_ref::<T>(self)
335 /// Forwards to the method defined on the type `dyn Error`.
336 #[stable(feature = "error_downcast", since = "1.3.0")]
338 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
339 <dyn Error + 'static>::downcast_mut::<T>(self)
342 /// Request a reference of type `T` as context about this error.
343 #[unstable(feature = "error_generic_member_access", issue = "99301")]
344 pub fn request_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
345 <dyn Error>::request_ref(self)
348 /// Request a value of type `T` as context about this error.
349 #[unstable(feature = "error_generic_member_access", issue = "99301")]
350 pub fn request_value<T: 'static>(&self) -> Option<T> {
351 <dyn Error>::request_value(self)
356 /// Returns an iterator starting with the current error and continuing with
357 /// recursively calling [`Error::source`].
359 /// If you want to omit the current error and only use its sources,
365 /// #![feature(error_iter)]
366 /// use std::error::Error;
373 /// struct B(Option<Box<dyn Error + 'static>>);
375 /// impl fmt::Display for A {
376 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381 /// impl fmt::Display for B {
382 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387 /// impl Error for A {}
389 /// impl Error for B {
390 /// fn source(&self) -> Option<&(dyn Error + 'static)> {
391 /// self.0.as_ref().map(|e| e.as_ref())
395 /// let b = B(Some(Box::new(A)));
397 /// // let err : Box<Error> = b.into(); // or
398 /// let err = &b as &(dyn Error);
400 /// let mut iter = err.chain();
402 /// assert_eq!("B".to_string(), iter.next().unwrap().to_string());
403 /// assert_eq!("A".to_string(), iter.next().unwrap().to_string());
404 /// assert!(iter.next().is_none());
405 /// assert!(iter.next().is_none());
407 #[unstable(feature = "error_iter", issue = "58520")]
409 pub fn chain(&self) -> Chain<'_> {
410 Chain { current: Some(self) }
414 /// An iterator over an [`Error`] and its sources.
416 /// If you want to omit the initial error and only process
417 /// its sources, use `skip(1)`.
418 #[unstable(feature = "error_iter", issue = "58520")]
419 #[derive(Clone, Debug)]
420 pub struct Chain<'a> {
421 current: Option<&'a (dyn Error + 'static)>,
424 #[unstable(feature = "error_iter", issue = "58520")]
425 impl<'a> Iterator for Chain<'a> {
426 type Item = &'a (dyn Error + 'static);
428 fn next(&mut self) -> Option<Self::Item> {
429 let current = self.current;
430 self.current = self.current.and_then(Error::source);
435 #[stable(feature = "error_by_ref", since = "1.51.0")]
436 impl<'a, T: Error + ?Sized> Error for &'a T {
437 #[allow(deprecated, deprecated_in_future)]
438 fn description(&self) -> &str {
439 Error::description(&**self)
443 fn cause(&self) -> Option<&dyn Error> {
444 Error::cause(&**self)
447 fn source(&self) -> Option<&(dyn Error + 'static)> {
448 Error::source(&**self)
451 fn provide<'b>(&'b self, req: &mut Demand<'b>) {
452 Error::provide(&**self, req);
456 #[stable(feature = "fmt_error", since = "1.11.0")]
457 impl Error for crate::fmt::Error {
459 fn description(&self) -> &str {
460 "an error occurred when formatting an argument"
464 #[stable(feature = "try_borrow", since = "1.13.0")]
465 impl Error for crate::cell::BorrowError {
467 fn description(&self) -> &str {
468 "already mutably borrowed"
472 #[stable(feature = "try_borrow", since = "1.13.0")]
473 impl Error for crate::cell::BorrowMutError {
475 fn description(&self) -> &str {
480 #[stable(feature = "try_from", since = "1.34.0")]
481 impl Error for crate::char::CharTryFromError {
483 fn description(&self) -> &str {
484 "converted integer out of range for `char`"
488 #[stable(feature = "char_from_str", since = "1.20.0")]
489 impl Error for crate::char::ParseCharError {
491 fn description(&self) -> &str {
496 #[unstable(feature = "duration_checked_float", issue = "83400")]
497 impl Error for crate::time::FromFloatSecsError {}
499 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
500 impl Error for crate::ffi::FromBytesWithNulError {
502 fn description(&self) -> &str {
507 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
508 impl Error for crate::ffi::FromBytesUntilNulError {}