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.
58 use fmt::{self, Debug, Display};
64 /// Base functionality for all errors in Rust.
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub trait Error: Debug + Display {
67 /// A short description of the error.
69 /// The description should only be used for a simple message.
70 /// It should not contain newlines or sentence-ending punctuation,
71 /// to facilitate embedding in larger user-facing strings.
72 /// For showing formatted error messages with more information see
75 /// [`Display`]: ../fmt/trait.Display.html
80 /// use std::error::Error;
82 /// match "xc".parse::<u32>() {
84 /// println!("Error: {}", e.description());
86 /// _ => println!("No error"),
89 #[stable(feature = "rust1", since = "1.0.0")]
90 fn description(&self) -> &str;
92 /// The lower-level cause of this error, if any.
97 /// use std::error::Error;
101 /// struct SuperError {
102 /// side: SuperErrorSideKick,
105 /// impl fmt::Display for SuperError {
106 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
107 /// write!(f, "SuperError is here!")
111 /// impl Error for SuperError {
112 /// fn description(&self) -> &str {
113 /// "I'm the superhero of errors"
116 /// fn cause(&self) -> Option<&Error> {
122 /// struct SuperErrorSideKick;
124 /// impl fmt::Display for SuperErrorSideKick {
125 /// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126 /// write!(f, "SuperErrorSideKick is here!")
130 /// impl Error for SuperErrorSideKick {
131 /// fn description(&self) -> &str {
132 /// "I'm SuperError side kick"
136 /// fn get_super_error() -> Result<(), SuperError> {
137 /// Err(SuperError { side: SuperErrorSideKick })
141 /// match get_super_error() {
143 /// println!("Error: {}", e.description());
144 /// println!("Caused by: {}", e.cause().unwrap());
146 /// _ => println!("No error"),
150 #[stable(feature = "rust1", since = "1.0.0")]
151 fn cause(&self) -> Option<&Error> { None }
153 /// Get the `TypeId` of `self`
155 #[unstable(feature = "error_type_id",
156 reason = "unclear whether to commit to this public implementation detail",
158 fn type_id(&self) -> TypeId where Self: 'static {
163 #[stable(feature = "rust1", since = "1.0.0")]
164 impl<'a, E: Error + 'a> From<E> for Box<Error + 'a> {
165 fn from(err: E) -> Box<Error + 'a> {
170 #[stable(feature = "rust1", since = "1.0.0")]
171 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<Error + Send + Sync + 'a> {
172 fn from(err: E) -> Box<Error + Send + Sync + 'a> {
177 #[stable(feature = "rust1", since = "1.0.0")]
178 impl From<String> for Box<Error + Send + Sync> {
179 fn from(err: String) -> Box<Error + Send + Sync> {
181 struct StringError(String);
183 impl Error for StringError {
184 fn description(&self) -> &str { &self.0 }
187 impl Display for StringError {
188 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
189 Display::fmt(&self.0, f)
193 Box::new(StringError(err))
197 #[stable(feature = "string_box_error", since = "1.6.0")]
198 impl From<String> for Box<Error> {
199 fn from(str_err: String) -> Box<Error> {
200 let err1: Box<Error + Send + Sync> = From::from(str_err);
201 let err2: Box<Error> = err1;
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<'a, 'b> From<&'b str> for Box<Error + Send + Sync + 'a> {
208 fn from(err: &'b str) -> Box<Error + Send + Sync + 'a> {
209 From::from(String::from(err))
213 #[stable(feature = "string_box_error", since = "1.6.0")]
214 impl<'a> From<&'a str> for Box<Error> {
215 fn from(err: &'a str) -> Box<Error> {
216 From::from(String::from(err))
220 #[unstable(feature = "never_type_impls", issue = "35121")]
222 fn description(&self) -> &str { *self }
225 #[unstable(feature = "allocator_api",
226 reason = "the precise API and guarantees it provides may be tweaked.",
228 impl Error for allocator::AllocErr {
229 fn description(&self) -> &str {
230 allocator::AllocErr::description(self)
234 #[unstable(feature = "allocator_api",
235 reason = "the precise API and guarantees it provides may be tweaked.",
237 impl Error for allocator::CannotReallocInPlace {
238 fn description(&self) -> &str {
239 allocator::CannotReallocInPlace::description(self)
243 #[stable(feature = "rust1", since = "1.0.0")]
244 impl Error for str::ParseBoolError {
245 fn description(&self) -> &str { "failed to parse bool" }
248 #[stable(feature = "rust1", since = "1.0.0")]
249 impl Error for str::Utf8Error {
250 fn description(&self) -> &str {
251 "invalid utf-8: corrupt contents"
255 #[stable(feature = "rust1", since = "1.0.0")]
256 impl Error for num::ParseIntError {
257 fn description(&self) -> &str {
262 #[unstable(feature = "try_from", issue = "33417")]
263 impl Error for num::TryFromIntError {
264 fn description(&self) -> &str {
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl Error for num::ParseFloatError {
271 fn description(&self) -> &str {
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl Error for string::FromUtf8Error {
278 fn description(&self) -> &str {
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl Error for string::FromUtf16Error {
285 fn description(&self) -> &str {
290 #[stable(feature = "str_parse_error2", since = "1.8.0")]
291 impl Error for string::ParseError {
292 fn description(&self) -> &str {
297 #[stable(feature = "decode_utf16", since = "1.9.0")]
298 impl Error for char::DecodeUtf16Error {
299 fn description(&self) -> &str {
300 "unpaired surrogate found"
304 #[stable(feature = "box_error", since = "1.8.0")]
305 impl<T: Error> Error for Box<T> {
306 fn description(&self) -> &str {
307 Error::description(&**self)
310 fn cause(&self) -> Option<&Error> {
311 Error::cause(&**self)
315 #[stable(feature = "fmt_error", since = "1.11.0")]
316 impl Error for fmt::Error {
317 fn description(&self) -> &str {
318 "an error occurred when formatting an argument"
322 #[stable(feature = "try_borrow", since = "1.13.0")]
323 impl Error for cell::BorrowError {
324 fn description(&self) -> &str {
325 "already mutably borrowed"
329 #[stable(feature = "try_borrow", since = "1.13.0")]
330 impl Error for cell::BorrowMutError {
331 fn description(&self) -> &str {
336 #[unstable(feature = "try_from", issue = "33417")]
337 impl Error for char::CharTryFromError {
338 fn description(&self) -> &str {
339 "converted integer out of range for `char`"
343 #[stable(feature = "char_from_str", since = "1.19.0")]
344 impl Error for char::ParseCharError {
345 fn description(&self) -> &str {
351 // copied from any.rs
352 impl Error + 'static {
353 /// Returns true if the boxed type is the same as `T`
354 #[stable(feature = "error_downcast", since = "1.3.0")]
356 pub fn is<T: Error + 'static>(&self) -> bool {
357 // Get TypeId of the type this function is instantiated with
358 let t = TypeId::of::<T>();
360 // Get TypeId of the type in the trait object
361 let boxed = self.type_id();
363 // Compare both TypeIds on equality
367 /// Returns some reference to the boxed value if it is of type `T`, or
368 /// `None` if it isn't.
369 #[stable(feature = "error_downcast", since = "1.3.0")]
371 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
374 Some(&*(self as *const Error as *const T))
381 /// Returns some mutable reference to the boxed value if it is of type `T`, or
382 /// `None` if it isn't.
383 #[stable(feature = "error_downcast", since = "1.3.0")]
385 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
388 Some(&mut *(self as *mut Error as *mut T))
396 impl Error + 'static + Send {
397 /// Forwards to the method defined on the type `Any`.
398 #[stable(feature = "error_downcast", since = "1.3.0")]
400 pub fn is<T: Error + 'static>(&self) -> bool {
401 <Error + 'static>::is::<T>(self)
404 /// Forwards to the method defined on the type `Any`.
405 #[stable(feature = "error_downcast", since = "1.3.0")]
407 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
408 <Error + 'static>::downcast_ref::<T>(self)
411 /// Forwards to the method defined on the type `Any`.
412 #[stable(feature = "error_downcast", since = "1.3.0")]
414 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
415 <Error + 'static>::downcast_mut::<T>(self)
419 impl Error + 'static + Send + Sync {
420 /// Forwards to the method defined on the type `Any`.
421 #[stable(feature = "error_downcast", since = "1.3.0")]
423 pub fn is<T: Error + 'static>(&self) -> bool {
424 <Error + 'static>::is::<T>(self)
427 /// Forwards to the method defined on the type `Any`.
428 #[stable(feature = "error_downcast", since = "1.3.0")]
430 pub fn downcast_ref<T: Error + 'static>(&self) -> Option<&T> {
431 <Error + 'static>::downcast_ref::<T>(self)
434 /// Forwards to the method defined on the type `Any`.
435 #[stable(feature = "error_downcast", since = "1.3.0")]
437 pub fn downcast_mut<T: Error + 'static>(&mut self) -> Option<&mut T> {
438 <Error + 'static>::downcast_mut::<T>(self)
444 #[stable(feature = "error_downcast", since = "1.3.0")]
445 /// Attempt to downcast the box to a concrete type.
446 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Error>> {
449 let raw: *mut Error = Box::into_raw(self);
450 Ok(Box::from_raw(raw as *mut T))
460 #[stable(feature = "error_downcast", since = "1.3.0")]
461 /// Attempt to downcast the box to a concrete type.
462 pub fn downcast<T: Error + 'static>(self: Box<Self>)
463 -> Result<Box<T>, Box<Error + Send>> {
464 let err: Box<Error> = self;
465 <Error>::downcast(err).map_err(|s| unsafe {
466 // reapply the Send marker
467 transmute::<Box<Error>, Box<Error + Send>>(s)
472 impl Error + Send + Sync {
474 #[stable(feature = "error_downcast", since = "1.3.0")]
475 /// Attempt to downcast the box to a concrete type.
476 pub fn downcast<T: Error + 'static>(self: Box<Self>)
477 -> Result<Box<T>, Box<Self>> {
478 let err: Box<Error> = self;
479 <Error>::downcast(err).map_err(|s| unsafe {
480 // reapply the Send+Sync marker
481 transmute::<Box<Error>, Box<Error + Send + Sync>>(s)
491 #[derive(Debug, PartialEq)]
493 #[derive(Debug, PartialEq)]
496 impl fmt::Display for A {
497 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
501 impl fmt::Display for B {
502 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
508 fn description(&self) -> &str { "A-desc" }
511 fn description(&self) -> &str { "A-desc" }
517 let mut a = &mut a as &mut (Error + 'static);
518 assert_eq!(a.downcast_ref::<A>(), Some(&A));
519 assert_eq!(a.downcast_ref::<B>(), None);
520 assert_eq!(a.downcast_mut::<A>(), Some(&mut A));
521 assert_eq!(a.downcast_mut::<B>(), None);
523 let a: Box<Error> = Box::new(A);
524 match a.downcast::<B>() {
525 Ok(..) => panic!("expected error"),
526 Err(e) => assert_eq!(*e.downcast::<A>().unwrap(), A),