1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Traits for working with Errors.
13 //! # The `Error` trait
15 //! `Error` is a trait representing the basic expectations for error values,
16 //! i.e. values of type `E` in [`Result<T, E>`]. At a minimum, errors must provide
17 //! a description, but they may optionally provide additional detail (via
18 //! [`Display`]) and cause chain information:
21 //! use std::fmt::Display;
23 //! trait Error: Display {
24 //! fn description(&self) -> &str;
26 //! fn cause(&self) -> Option<&Error> { None }
30 //! The [`cause`] method is generally used when errors cross "abstraction
31 //! boundaries", i.e. when a one module must report an error that is "caused"
32 //! by an error from a lower-level module. This setup makes it possible for the
33 //! high-level module to provide its own errors that do not commit to any
34 //! particular implementation, but also reveal some of its implementation for
35 //! debugging via [`cause`] chains.
37 //! [`Result<T, E>`]: ../result/enum.Result.html
38 //! [`Display`]: ../fmt/trait.Display.html
39 //! [`cause`]: trait.Error.html#method.cause
41 #![stable(feature = "rust1", since = "1.0.0")]
43 // A note about crates and the facade:
45 // Originally, the `Error` trait was defined in libcore, and the impls
46 // were scattered about. However, coherence objected to this
47 // arrangement, because to create the blanket impls for `Box` required
48 // knowing that `&str: !Error`, and we have no means to deal with that
49 // sort of conflict just now. Therefore, for the time being, we have
50 // moved the `Error` trait into libstd. As we evolve a sol'n to the
51 // coherence challenge (e.g., specialization, neg impls, etc) we can
52 // reconsider what crate these items belong in.
59 use fmt::{self, Debug, Display};
65 /// Base functionality for all errors in Rust.
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub trait Error: Debug + Display {
68 /// A short description of the error.
70 /// The description should only be used for a simple message.
71 /// It should not contain newlines or sentence-ending punctuation,
72 /// to facilitate embedding in larger user-facing strings.
73 /// For showing formatted error messages with more information see
76 /// [`Display`]: ../fmt/trait.Display.html
81 /// use std::error::Error;
83 /// match "xc".parse::<u32>() {
85 /// println!("Error: {}", e.description());
87 /// _ => println!("No error"),
90 #[stable(feature = "rust1", since = "1.0.0")]
91 fn description(&self) -> &str;
93 /// The lower-level cause of this error, if any.
98 /// use std::error::Error;
102 /// struct SuperError {
103 /// side: SuperErrorSideKick,
106 /// impl fmt::Display for SuperError {
107 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 /// write!(f, "SuperError is here!")
112 /// impl Error for SuperError {
113 /// fn description(&self) -> &str {
114 /// "I'm the superhero of errors"
117 /// fn cause(&self) -> Option<&Error> {
123 /// struct SuperErrorSideKick;
125 /// impl fmt::Display for SuperErrorSideKick {
126 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
127 /// write!(f, "SuperErrorSideKick is here!")
131 /// impl Error for SuperErrorSideKick {
132 /// fn description(&self) -> &str {
133 /// "I'm SuperError side kick"
137 /// fn get_super_error() -> Result<(), SuperError> {
138 /// Err(SuperError { side: SuperErrorSideKick })
142 /// match get_super_error() {
144 /// println!("Error: {}", e.description());
145 /// println!("Caused by: {}", e.cause().unwrap());
147 /// _ => println!("No error"),
151 #[stable(feature = "rust1", since = "1.0.0")]
152 fn cause(&self) -> Option<&Error> { None }
154 /// Get the `TypeId` of `self`
156 #[unstable(feature = "error_type_id",
157 reason = "unclear whether to commit to this public implementation detail",
159 fn type_id(&self) -> TypeId where Self: 'static {
164 #[stable(feature = "rust1", since = "1.0.0")]
165 impl<'a, E: Error + 'a> From<E> for Box<Error + 'a> {
166 fn from(err: E) -> Box<Error + 'a> {
171 #[stable(feature = "rust1", since = "1.0.0")]
172 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<Error + Send + Sync + 'a> {
173 fn from(err: E) -> Box<Error + Send + Sync + 'a> {
178 #[stable(feature = "rust1", since = "1.0.0")]
179 impl From<String> for Box<Error + Send + Sync> {
180 fn from(err: String) -> Box<Error + Send + Sync> {
182 struct StringError(String);
184 impl Error for StringError {
185 fn description(&self) -> &str { &self.0 }
188 impl Display for StringError {
189 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
190 Display::fmt(&self.0, f)
194 Box::new(StringError(err))
198 #[stable(feature = "string_box_error", since = "1.6.0")]
199 impl From<String> for Box<Error> {
200 fn from(str_err: String) -> Box<Error> {
201 let err1: Box<Error + Send + Sync> = From::from(str_err);
202 let err2: Box<Error> = err1;
207 #[stable(feature = "rust1", since = "1.0.0")]
208 impl<'a, 'b> From<&'b str> for Box<Error + Send + Sync + 'a> {
209 fn from(err: &'b str) -> Box<Error + Send + Sync + 'a> {
210 From::from(String::from(err))
214 #[stable(feature = "string_box_error", since = "1.6.0")]
215 impl<'a> From<&'a str> for Box<Error> {
216 fn from(err: &'a str) -> Box<Error> {
217 From::from(String::from(err))
221 #[stable(feature = "cow_box_error", since = "1.22.0")]
222 impl<'a, 'b> From<Cow<'b, str>> for Box<Error + Send + Sync + 'a> {
223 fn from(err: Cow<'b, str>) -> Box<Error + Send + Sync + 'a> {
224 From::from(String::from(err))
228 #[stable(feature = "cow_box_error", since = "1.22.0")]
229 impl<'a> From<Cow<'a, str>> for Box<Error> {
230 fn from(err: Cow<'a, str>) -> Box<Error> {
231 From::from(String::from(err))
235 #[unstable(feature = "never_type_impls", issue = "35121")]
237 fn description(&self) -> &str { *self }
240 #[unstable(feature = "allocator_api",
241 reason = "the precise API and guarantees it provides may be tweaked.",
243 impl Error for allocator::AllocErr {
244 fn description(&self) -> &str {
245 allocator::AllocErr::description(self)
249 #[unstable(feature = "allocator_api",
250 reason = "the precise API and guarantees it provides may be tweaked.",
252 impl Error for allocator::CannotReallocInPlace {
253 fn description(&self) -> &str {
254 allocator::CannotReallocInPlace::description(self)
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl Error for str::ParseBoolError {
260 fn description(&self) -> &str { "failed to parse bool" }
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl Error for str::Utf8Error {
265 fn description(&self) -> &str {
266 "invalid utf-8: corrupt contents"
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl Error for num::ParseIntError {
272 fn description(&self) -> &str {
277 #[unstable(feature = "try_from", issue = "33417")]
278 impl Error for num::TryFromIntError {
279 fn description(&self) -> &str {
284 #[stable(feature = "rust1", since = "1.0.0")]
285 impl Error for num::ParseFloatError {
286 fn description(&self) -> &str {
291 #[stable(feature = "rust1", since = "1.0.0")]
292 impl Error for string::FromUtf8Error {
293 fn description(&self) -> &str {
298 #[stable(feature = "rust1", since = "1.0.0")]
299 impl Error for string::FromUtf16Error {
300 fn description(&self) -> &str {
305 #[stable(feature = "str_parse_error2", since = "1.8.0")]
306 impl Error for string::ParseError {
307 fn description(&self) -> &str {
312 #[stable(feature = "decode_utf16", since = "1.9.0")]
313 impl Error for char::DecodeUtf16Error {
314 fn description(&self) -> &str {
315 "unpaired surrogate found"
319 #[stable(feature = "box_error", since = "1.8.0")]
320 impl<T: Error> Error for Box<T> {
321 fn description(&self) -> &str {
322 Error::description(&**self)
325 fn cause(&self) -> Option<&Error> {
326 Error::cause(&**self)
330 #[stable(feature = "fmt_error", since = "1.11.0")]
331 impl Error for fmt::Error {
332 fn description(&self) -> &str {
333 "an error occurred when formatting an argument"
337 #[stable(feature = "try_borrow", since = "1.13.0")]
338 impl Error for cell::BorrowError {
339 fn description(&self) -> &str {
340 "already mutably borrowed"
344 #[stable(feature = "try_borrow", since = "1.13.0")]
345 impl Error for cell::BorrowMutError {
346 fn description(&self) -> &str {
351 #[unstable(feature = "try_from", issue = "33417")]
352 impl Error for char::CharTryFromError {
353 fn description(&self) -> &str {
354 "converted integer out of range for `char`"
358 #[stable(feature = "char_from_str", since = "1.20.0")]
359 impl Error for char::ParseCharError {
360 fn description(&self) -> &str {
366 // copied from any.rs
367 impl Error + 'static {
368 /// Returns true if the boxed type is the same as `T`
369 #[stable(feature = "error_downcast", since = "1.3.0")]
371 pub fn is<T: Error + 'static>(&self) -> bool {
372 // Get TypeId of the type this function is instantiated with
373 let t = TypeId::of::<T>();
375 // Get TypeId of the type in the trait object
376 let boxed = self.type_id();
378 // Compare both TypeIds on equality
382 /// Returns some reference to the boxed value if it is of type `T`, or
383 /// `None` if it isn't.
384 #[stable(feature = "error_downcast", since = "1.3.0")]
386 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
389 Some(&*(self as *const Error as *const T))
396 /// Returns some mutable reference to the boxed value if it is of type `T`, or
397 /// `None` if it isn't.
398 #[stable(feature = "error_downcast", since = "1.3.0")]
400 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
403 Some(&mut *(self as *mut Error as *mut T))
411 impl Error + 'static + Send {
412 /// Forwards to the method defined on the type `Any`.
413 #[stable(feature = "error_downcast", since = "1.3.0")]
415 pub fn is<T: Error + 'static>(&self) -> bool {
416 <Error + 'static>::is::<T>(self)
419 /// Forwards to the method defined on the type `Any`.
420 #[stable(feature = "error_downcast", since = "1.3.0")]
422 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
423 <Error + 'static>::downcast_ref::<T>(self)
426 /// Forwards to the method defined on the type `Any`.
427 #[stable(feature = "error_downcast", since = "1.3.0")]
429 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
430 <Error + 'static>::downcast_mut::<T>(self)
434 impl Error + 'static + Send + Sync {
435 /// Forwards to the method defined on the type `Any`.
436 #[stable(feature = "error_downcast", since = "1.3.0")]
438 pub fn is<T: Error + 'static>(&self) -> bool {
439 <Error + 'static>::is::<T>(self)
442 /// Forwards to the method defined on the type `Any`.
443 #[stable(feature = "error_downcast", since = "1.3.0")]
445 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
446 <Error + 'static>::downcast_ref::<T>(self)
449 /// Forwards to the method defined on the type `Any`.
450 #[stable(feature = "error_downcast", since = "1.3.0")]
452 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
453 <Error + 'static>::downcast_mut::<T>(self)
459 #[stable(feature = "error_downcast", since = "1.3.0")]
460 /// Attempt to downcast the box to a concrete type.
461 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
464 let raw: *mut Error = Box::into_raw(self);
465 Ok(Box::from_raw(raw as *mut T))
475 #[stable(feature = "error_downcast", since = "1.3.0")]
476 /// Attempt to downcast the box to a concrete type.
477 pub fn downcast<T: Error + 'static>(self: Box<Self>)
478 -> Result<Box<T>, Box<Error + Send>> {
479 let err: Box<Error> = self;
480 <Error>::downcast(err).map_err(|s| unsafe {
481 // reapply the Send marker
482 transmute::<Box<Error>, Box<Error + Send>>(s)
487 impl Error + Send + Sync {
489 #[stable(feature = "error_downcast", since = "1.3.0")]
490 /// Attempt to downcast the box to a concrete type.
491 pub fn downcast<T: Error + 'static>(self: Box<Self>)
492 -> Result<Box<T>, Box<Self>> {
493 let err: Box<Error> = self;
494 <Error>::downcast(err).map_err(|s| unsafe {
495 // reapply the Send+Sync marker
496 transmute::<Box<Error>, Box<Error + Send + Sync>>(s)
506 #[derive(Debug, PartialEq)]
508 #[derive(Debug, PartialEq)]
511 impl fmt::Display for A {
512 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516 impl fmt::Display for B {
517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523 fn description(&self) -> &str { "A-desc" }
526 fn description(&self) -> &str { "A-desc" }
532 let a = &mut a as &mut (Error + 'static);
533 assert_eq!(a.downcast_ref::<A>(), Some(&A));
534 assert_eq!(a.downcast_ref::<B>(), None);
535 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
536 assert_eq!(a.downcast_mut::<B>(), None);
538 let a: Box<Error> = Box::new(A);
539 match a.downcast::<B>() {
540 Ok(..) => panic!("expected error"),
541 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),