Skip to content
Myr

Rename exception module 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 27b8f24 · Browse files · 3 files+319 added−319 removed
This commit

State

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

Diff stats

3 files+319 added−319 removed

  • other:+319 added−319 removed

3 files+319 added−319 removed

added:src/error.rs+317 added
1use std::any::TypeId;2use std::backtrace::{Backtrace, BacktraceStatus};3use std::error::Error;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// The `Exception type, a wrapper around a dynamic error type.10///11/// `Exception` functions a lot like `Box<dyn 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 type15/// did not provide one16/// - `Exception` is represented as a narrow pointer - exactly one word in size,17/// instead of two.18pub struct Exception {19 inner: Box<InnerException<()>>,20}2122impl Exception {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.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) -> Exception30 where31 E: Error + Send + Sync + 'static,32 {33 Exception::construct(error, TypeId::of::<E>())34 }3536 #[doc(hidden)]37 pub fn new_adhoc<M>(message: M) -> Exception38 where39 M: Display + Debug + Send + Sync + 'static,40 {41 Exception::construct(MessageError(message), TypeId::of::<M>())42 }4344 fn construct<E>(error: E, type_id: TypeId) -> Exception45 where46 E: Error + Send + Sync + 'static,47 {48 unsafe {49 let backtrace = match error.backtrace() {50 Some(_) => None,51 None => Some(Backtrace::capture()),52 };53 let obj: TraitObject = mem::transmute(&error as &dyn Error);54 let vtable = obj.vtable;55 let inner = InnerException {56 vtable,57 type_id,58 backtrace,59 error,60 };61 Exception {62 inner: mem::transmute(Box::new(inner)),63 }64 }65 }6667 /// View this exception as the underlying error.68 pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {69 &**self70 }7172 /// View this exception as the underlying error, mutably.73 pub fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {74 &mut **self75 }7677 /// Get the backtrace for this Exception.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.inner82 .backtrace83 .as_ref()84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }8788 /// An iterator of errors contained by this Exception.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<'_> {93 Errors {94 next: Some(self.inner.error()),95 }96 }9798 /// Returns `true` if `E` is the type wrapped by this exception.99 pub fn is<E: Display + Debug + Send + Sync + 'static>(&self) -> bool {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> {105 if let Some(error) = self.downcast_ref::<E>() {106 unsafe {107 let error = ptr::read(error);108 drop(ptr::read(&self.inner));109 mem::forget(self);110 Ok(error)111 }112 } else {113 Err(self)114 }115 }116117 /// Downcast this exception by reference.118 pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119 if self.is::<E>() {120 unsafe { Some(&*(self.inner.error() as *const dyn Error as *const E)) }121 } else {122 None123 }124 }125126 /// Downcast this exception by mutable reference.127 pub fn downcast_mut<E: Display + Debug + Send + Sync + 'static>(&mut self) -> Option<&mut E> {128 if self.is::<E>() {129 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }130 } else {131 None132 }133 }134}135136impl<E: Error + Send + Sync + 'static> From<E> for Exception {137 fn from(error: E) -> Exception {138 Exception::new(error)139 }140}141142impl Deref for Exception {143 type Target = dyn Error + Send + Sync + 'static;144 fn deref(&self) -> &Self::Target {145 self.inner.error()146 }147}148149impl DerefMut for Exception {150 fn deref_mut(&mut self) -> &mut Self::Target {151 self.inner.error_mut()152 }153}154155impl Debug for Exception {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();160161 if let Some((n, error)) = errors.next() {162 writeln!(f, "\ncaused by:")?;163 writeln!(f, "\t{}: {}", n, error)?;164 for (n, error) in errors {165 writeln!(f, "\t{}: {}", n, error)?;166 }167 }168169 let backtrace = self.backtrace();170171 match backtrace.status() {172 BacktraceStatus::Captured => {173 writeln!(f, "\n{}", backtrace)?;174 }175 BacktraceStatus::Disabled => {176 writeln!(177 f,178 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \179 to display a backtrace"180 )?;181 }182 _ => {}183 }184185 Ok(())186 }187}188189impl Display for Exception {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 {}197198impl Drop for Exception {199 fn drop(&mut self) {200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }201 }202}203204// repr C to ensure that `E` remains in the final position205#[repr(C)]206struct InnerException<E> {207 vtable: *const (),208 type_id: TypeId,209 backtrace: Option<Backtrace>,210 error: E,211}212213// repr C to ensure that transmuting from trait objects is safe214#[repr(C)]215struct TraitObject {216 data: *const (),217 vtable: *const (),218}219220#[repr(transparent)]221struct MessageError<M: Display + Debug>(M);222223impl<M: Display + Debug> Debug for MessageError<M> {224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {225 Debug::fmt(&self.0, f)226 }227}228229impl<M: Display + Debug> Display for MessageError<M> {230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {231 Display::fmt(&self.0, f)232 }233}234235impl<M: Display + Debug + 'static> Error for MessageError<M> {}236237impl InnerException<()> {238 fn error(&self) -> &(dyn Error + Send + Sync + 'static) {239 unsafe {240 mem::transmute(TraitObject {241 data: &self.error,242 vtable: self.vtable,243 })244 }245 }246247 fn error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {248 unsafe {249 mem::transmute(TraitObject {250 data: &mut self.error,251 vtable: self.vtable,252 })253 }254 }255}256257/// Iterator of errors in an `Exception`.258pub struct Errors<'a> {259 next: Option<&'a (dyn Error + 'static)>,260}261262impl<'a> Iterator for Errors<'a> {263 type Item = &'a (dyn Error + 'static);264265 fn next(&mut self) -> Option<Self::Item> {266 let next = self.next.take()?;267 self.next = next.source();268 Some(next)269 }270}271272#[cfg(test)]273mod repr_correctness {274 use super::*;275276 use std::marker::Unpin;277 use std::mem;278279 #[test]280 fn size_of_exception() {281 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282 }283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where287 Exception: Unpin + Send + Sync + 'static,288 {289 }290291 #[test]292 fn destructors_work() {293 use std::sync::*;294295 #[derive(Debug)]296 struct HasDrop(Box<Arc<Mutex<bool>>>);297 impl Error for HasDrop {}298 impl Display for HasDrop {299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {300 write!(f, "does something")301 }302 }303 impl Drop for HasDrop {304 fn drop(&mut self) {305 let mut has_dropped = self.0.lock().unwrap();306 assert!(!*has_dropped);307 *has_dropped = true;308 }309 }310311 let has_dropped = Arc::new(Mutex::new(false));312313 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314315 assert!(*has_dropped.lock().unwrap());316 }317}
deleted:src/exception.rs-317 removed
1use std::any::TypeId;2use std::backtrace::{Backtrace, BacktraceStatus};3use std::error::Error;4use std::fmt::{self, Debug, Display};5use std::mem;6use std::ops::{Deref, DerefMut};7use std::ptr;89/// The `Exception type, a wrapper around a dynamic error type.10///11/// `Exception` functions a lot like `Box<dyn 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 type15/// did not provide one16/// - `Exception` is represented as a narrow pointer - exactly one word in size,17/// instead of two.18pub struct Exception {19 inner: Box<InnerException<()>>,20}2122impl Exception {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.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) -> Exception30 where31 E: Error + Send + Sync + 'static,32 {33 Exception::construct(error, TypeId::of::<E>())34 }3536 #[doc(hidden)]37 pub fn new_adhoc<M>(message: M) -> Exception38 where39 M: Display + Debug + Send + Sync + 'static,40 {41 Exception::construct(MessageError(message), TypeId::of::<M>())42 }4344 fn construct<E>(error: E, type_id: TypeId) -> Exception45 where46 E: Error + Send + Sync + 'static,47 {48 unsafe {49 let backtrace = match error.backtrace() {50 Some(_) => None,51 None => Some(Backtrace::capture()),52 };53 let obj: TraitObject = mem::transmute(&error as &dyn Error);54 let vtable = obj.vtable;55 let inner = InnerException {56 vtable,57 type_id,58 backtrace,59 error,60 };61 Exception {62 inner: mem::transmute(Box::new(inner)),63 }64 }65 }6667 /// View this exception as the underlying error.68 pub fn as_error(&self) -> &(dyn Error + Send + Sync + 'static) {69 &**self70 }7172 /// View this exception as the underlying error, mutably.73 pub fn as_error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {74 &mut **self75 }7677 /// Get the backtrace for this Exception.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.inner82 .backtrace83 .as_ref()84 .or_else(|| self.inner.error().backtrace())85 .expect("exception backtrace capture failed")86 }8788 /// An iterator of errors contained by this Exception.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<'_> {93 Errors {94 next: Some(self.inner.error()),95 }96 }9798 /// Returns `true` if `E` is the type wrapped by this exception.99 pub fn is<E: Display + Debug + Send + Sync + 'static>(&self) -> bool {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> {105 if let Some(error) = self.downcast_ref::<E>() {106 unsafe {107 let error = ptr::read(error);108 drop(ptr::read(&self.inner));109 mem::forget(self);110 Ok(error)111 }112 } else {113 Err(self)114 }115 }116117 /// Downcast this exception by reference.118 pub fn downcast_ref<E: Display + Debug + Send + Sync + 'static>(&self) -> Option<&E> {119 if self.is::<E>() {120 unsafe { Some(&*(self.inner.error() as *const dyn Error as *const E)) }121 } else {122 None123 }124 }125126 /// Downcast this exception by mutable reference.127 pub fn downcast_mut<E: Display + Debug + Send + Sync + 'static>(&mut self) -> Option<&mut E> {128 if self.is::<E>() {129 unsafe { Some(&mut *(self.inner.error_mut() as *mut dyn Error as *mut E)) }130 } else {131 None132 }133 }134}135136impl<E: Error + Send + Sync + 'static> From<E> for Exception {137 fn from(error: E) -> Exception {138 Exception::new(error)139 }140}141142impl Deref for Exception {143 type Target = dyn Error + Send + Sync + 'static;144 fn deref(&self) -> &Self::Target {145 self.inner.error()146 }147}148149impl DerefMut for Exception {150 fn deref_mut(&mut self) -> &mut Self::Target {151 self.inner.error_mut()152 }153}154155impl Debug for Exception {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();160161 if let Some((n, error)) = errors.next() {162 writeln!(f, "\ncaused by:")?;163 writeln!(f, "\t{}: {}", n, error)?;164 for (n, error) in errors {165 writeln!(f, "\t{}: {}", n, error)?;166 }167 }168169 let backtrace = self.backtrace();170171 match backtrace.status() {172 BacktraceStatus::Captured => {173 writeln!(f, "\n{}", backtrace)?;174 }175 BacktraceStatus::Disabled => {176 writeln!(177 f,178 "\nbacktrace disabled; run with RUST_BACKTRACE=1 environment variable \179 to display a backtrace"180 )?;181 }182 _ => {}183 }184185 Ok(())186 }187}188189impl Display for Exception {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 {}197198impl Drop for Exception {199 fn drop(&mut self) {200 unsafe { ptr::drop_in_place(self.inner.error_mut()) }201 }202}203204// repr C to ensure that `E` remains in the final position205#[repr(C)]206struct InnerException<E> {207 vtable: *const (),208 type_id: TypeId,209 backtrace: Option<Backtrace>,210 error: E,211}212213// repr C to ensure that transmuting from trait objects is safe214#[repr(C)]215struct TraitObject {216 data: *const (),217 vtable: *const (),218}219220#[repr(transparent)]221struct MessageError<M: Display + Debug>(M);222223impl<M: Display + Debug> Debug for MessageError<M> {224 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {225 Debug::fmt(&self.0, f)226 }227}228229impl<M: Display + Debug> Display for MessageError<M> {230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {231 Display::fmt(&self.0, f)232 }233}234235impl<M: Display + Debug + 'static> Error for MessageError<M> {}236237impl InnerException<()> {238 fn error(&self) -> &(dyn Error + Send + Sync + 'static) {239 unsafe {240 mem::transmute(TraitObject {241 data: &self.error,242 vtable: self.vtable,243 })244 }245 }246247 fn error_mut(&mut self) -> &mut (dyn Error + Send + Sync + 'static) {248 unsafe {249 mem::transmute(TraitObject {250 data: &mut self.error,251 vtable: self.vtable,252 })253 }254 }255}256257/// Iterator of errors in an `Exception`.258pub struct Errors<'a> {259 next: Option<&'a (dyn Error + 'static)>,260}261262impl<'a> Iterator for Errors<'a> {263 type Item = &'a (dyn Error + 'static);264265 fn next(&mut self) -> Option<Self::Item> {266 let next = self.next.take()?;267 self.next = next.source();268 Some(next)269 }270}271272#[cfg(test)]273mod repr_correctness {274 use super::*;275276 use std::marker::Unpin;277 use std::mem;278279 #[test]280 fn size_of_exception() {281 assert_eq!(mem::size_of::<Exception>(), mem::size_of::<usize>());282 }283284 #[allow(dead_code)]285 fn assert_exception_autotraits()286 where287 Exception: Unpin + Send + Sync + 'static,288 {289 }290291 #[test]292 fn destructors_work() {293 use std::sync::*;294295 #[derive(Debug)]296 struct HasDrop(Box<Arc<Mutex<bool>>>);297 impl Error for HasDrop {}298 impl Display for HasDrop {299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {300 write!(f, "does something")301 }302 }303 impl Drop for HasDrop {304 fn drop(&mut self) {305 let mut has_dropped = self.0.lock().unwrap();306 assert!(!*has_dropped);307 *has_dropped = true;308 }309 }310311 let has_dropped = Arc::new(Mutex::new(false));312313 drop(Exception::from(HasDrop(Box::new(has_dropped.clone()))));314315 assert!(*has_dropped.lock().unwrap());316 }317}
modified:src/lib.rs+2 added-2 removed
1#![feature(backtrace)]23mod as_error;4mod context;5mod exception;5mod error;67pub use crate::as_error::AsError;8pub use crate::context::Context;9pub use crate::exception::{Errors, Exception};9pub use crate::error::{Errors, Exception};1011/// Return early with an error.12///13/// This macro is equivalent to `return Err(From::from($err))`.
16 unmodified lines