Skip to content
Myr

Rename Exception to Error

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent 7afc190 · Browse files · 4 files+51 added−51 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+51 added−51 removed

  • other:+51 added−51 removed

4 files+51 added−51 removed

modified:src/as_error.rs+2 added-2 removed
1use std::error::Error as StdError;23use crate::Exception;3use crate::Error;45/// View type as an error object.6pub trait AsError {7 /// View type as an error object.
11 unmodified lines
19 self20 }21}2223impl AsError for Exception {23impl AsError for Error {24 fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {25 &**self26 }27}
modified:src/context.rs+14 added-14 removed
1use std::backtrace::Backtrace;2use std::error::Error as StdError;3use std::fmt::{self, Debug, Display};45use crate::Exception;5use crate::Error;67/// Provides the `context` method for `Result`.8pub trait Context<T, E> {9 /// Wrap the error value with additional context.10 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception>;10 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error>;1112 /// Wrap the error value with additional context lazily.13 fn with_context<C, F>(self, f: F) -> Result<T, Exception>13 fn with_context<C, F>(self, f: F) -> Result<T, Error>14 where15 C: Display + Send + Sync + 'static,16 F: FnOnce(&E) -> C;17}1819impl<T, E: StdError + Send + Sync + 'static> Context<T, E> for Result<T, E> {20 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {21 self.map_err(|error| Exception::from(ContextError { error, context }))20 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {21 self.map_err(|error| Error::from(ContextError { error, context }))22 }2324 fn with_context<C, F>(self, f: F) -> Result<T, Exception>24 fn with_context<C, F>(self, f: F) -> Result<T, Error>25 where26 C: Display + Send + Sync + 'static,27 F: FnOnce(&E) -> C,28 {29 self.map_err(|error| {30 Exception::from(ContextError {30 Error::from(ContextError {31 context: f(&error),32 error,33 })34 })35 }36}3738impl<T> Context<T, Exception> for Result<T, Exception> {39 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Exception> {40 self.map_err(|error| Exception::from(ContextError { error, context }))38impl<T> Context<T, Error> for Result<T, Error> {39 fn context<C: Display + Send + Sync + 'static>(self, context: C) -> Result<T, Error> {40 self.map_err(|error| Error::from(ContextError { error, context }))41 }4243 fn with_context<C, F>(self, f: F) -> Result<T, Exception>43 fn with_context<C, F>(self, f: F) -> Result<T, Error>44 where45 C: Display + Send + Sync + 'static,46 F: FnOnce(&Exception) -> C,46 F: FnOnce(&Error) -> C,47 {48 self.map_err(|error| {49 Exception::from(ContextError {49 Error::from(ContextError {50 context: f(&error),51 error,52 })53 })
30 unmodified lines
84 Some(&self.error)85 }86}8788impl<C: Display> StdError for ContextError<Exception, C> {88impl<C: Display> StdError for ContextError<Error, C> {89 fn backtrace(&self) -> Option<&Backtrace> {90 Some(self.error.backtrace())91 }92
8 unmodified lines
modified:src/error.rs+31 added-31 removed
4 unmodified lines
5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// The `Exception type, a wrapper around a dynamic error type.9/// The `Error` type, a wrapper around a dynamic error type.10///11/// `Exception` functions a lot like `Box<dyn Error>`, with these differences:11/// `Error` functions a lot like `Box<dyn std::error::Error>`, with these differences:12///13/// - `Exception` requires that the error is `Send`, `Sync`, and `'static`14/// - `Exception` guarantees that a backtrace will exist, even if the error type13/// - `Error` requires that the error is `Send`, `Sync`, and `'static`14/// - `Error` guarantees that a backtrace will exist, even if the error type15/// did not provide one16/// - `Exception` is represented as a narrow pointer - exactly one word in size,16/// - `Error` is represented as a narrow pointer - exactly one word in size,17/// instead of two.18pub struct Exception {18pub struct Error {19 inner: Box<InnerException<()>>,20}2122impl Exception {22impl Error {23 /// Create a new exception from any error type.24 ///25 /// The error type must be threadsafe and `'static`, so that the `Exception` will be as well.25 /// The error type must be threadsafe and `'static`, so that the `Error` will be as well.26 ///27 /// If the error type does not provide a backtrace, a backtrace will be created here to ensure28 /// that a backtrace exists.29 pub fn new<E>(error: E) -> Exception29 pub fn new<E>(error: E) -> Error30 where31 E: StdError + Send + Sync + 'static,32 {33 Exception::construct(error, TypeId::of::<E>())33 Error::construct(error, TypeId::of::<E>())34 }3536 #[doc(hidden)]37 pub fn new_adhoc<M>(message: M) -> Exception37 pub fn new_adhoc<M>(message: M) -> Error38 where39 M: Display + Debug + Send + Sync + 'static,40 {41 Exception::construct(MessageError(message), TypeId::of::<M>())41 Error::construct(MessageError(message), TypeId::of::<M>())42 }4344 fn construct<E>(error: E, type_id: TypeId) -> Exception44 fn construct<E>(error: E, type_id: TypeId) -> Error45 where46 E: StdError + Send + Sync + 'static,47 {48 unsafe {
8 unmodified lines
57 type_id,58 backtrace,59 error,60 };61 Exception {61 Error {62 inner: mem::transmute(Box::new(inner)),63 }64 }65 }
7 unmodified lines
73 pub fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {74 &mut **self75 }7677 /// Get the backtrace for this Exception.77 /// Get the backtrace for this Error.78 pub fn backtrace(&self) -> &Backtrace {79 // NB: this unwrap can only fail if the underlying error's backtrace method is80 // nondeterministic, which would only happen in maliciously constructed code81 self.inner
2 unmodified lines
84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }8788 /// An iterator of errors contained by this Exception.88 /// An iterator of errors contained by this Error.89 ///90 /// This iterator will visit every error in the "cause chain" of this exception, beginning with91 /// the error that this exception was created from.92 pub fn errors(&self) -> Errors<'_> {
7 unmodified lines
100 TypeId::of::<E>() == self.inner.type_id101 }102103 /// Attempt to downcast the exception to a concrete type.104 pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Exception> {104 pub fn downcast<E: Display + Debug + Send + Sync + 'static>(self) -> Result<E, Error> {105 if let Some(error) = self.downcast_ref::<E>() {106 unsafe {107 let error = ptr::read(error);108 drop(ptr::read(&self.inner));
23 unmodified lines
132 }133 }134}135136impl<E: StdError + Send + Sync + 'static> From<E> for Exception {137 fn from(error: E) -> Exception {138 Exception::new(error)136impl<E: StdError + Send + Sync + 'static> From<E> for Error {137 fn from(error: E) -> Error {138 Error::new(error)139 }140}141142impl Deref for Exception {142impl Deref for Error {143 type Target = dyn StdError + Send + Sync + 'static;144 fn deref(&self) -> &Self::Target {145 self.inner.error()146 }147}148149impl DerefMut for Exception {149impl DerefMut for Error {150 fn deref_mut(&mut self) -> &mut Self::Target {151 self.inner.error_mut()152 }153}154155impl Debug for Exception {155impl Debug for Error {156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {157 writeln!(f, "{}", self.inner.error())?;158159 let mut errors = self.errors().skip(1).enumerate();
25 unmodified lines
185 Ok(())186 }187}188189impl Display for Exception {189impl Display for Error {190 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {191 write!(f, "{}", self.inner.error())192 }193}194195unsafe impl Send for Exception {}196unsafe impl Sync for Exception {}195unsafe impl Send for Error {}196unsafe impl Sync for Error {}197198impl Drop for Exception {198impl Drop for Error {199 fn drop(&mut self) {200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }201 }202}
50 unmodified lines
253 }254 }255}256257/// Iterator of errors in an `Exception`.257/// Iterator of errors in an `Error`.258pub struct Errors<'a> {259 next: Option<&'a (dyn StdError + 'static)>,260}261
15 unmodified lines
277 use std::mem;278279 #[test]280 fn size_of_exception() {281 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());281 assert_eq!(mem::size_of::<Error>(), mem::size_of::<usize>());282 }283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where287 Exception: Unpin + Send + Sync + 'static,287 Error: Unpin + Send + Sync + 'static,288 {289 }290291 #[test]
17 unmodified lines
309 }310311 let has_dropped = Arc::new(Mutex::new(false));312313 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));313 drop(Error::from(HasDrop(Box::new(has_dropped.clone()))));314315 assert!(*has_dropped.lock().unwrap());316 }317}
modified:src/lib.rs+4 added-4 removed
4 unmodified lines
5mod error;67pub use crate::as_error::AsError;8pub use crate::context::Context;9pub use crate::error::{Errors, Exception};9pub use crate::error::{Error, Errors};1011/// Return early with an error.12///13/// This macro is equivalent to `return Err(From::from($err))`.
5 unmodified lines
19}2021/// Construct an ad-hoc exception from a string.22///23/// This evaluates to an `Exception`. It can take either just a string, or a format string with23/// This evaluates to an `Error`. It can take either just a string, or a format string with24/// arguments. It also can take any custom type which implements `Debug` and `Display`.25#[macro_export]26macro_rules! error {27 ($e:expr) => { $crate::Exception::new_adhoc($e) };28 ($($arg:tt)*) => { $crate::Exception::new_adhoc(format!($($arg)*)) };27 ($e:expr) => { $crate::Error::new_adhoc($e) };28 ($($arg:tt)*) => { $crate::Error::new_adhoc(format!($($arg)*)) };29}