1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
#![deny(missing_docs)] #![doc(html_root_url = "https://dabo.guru/rust/throw/throw/")] //! Throw! //! ------ //! //! Throw is a new experimental rust error handling library, meant to assist and build on existing //! error handling systems. //! //! Throw exports two structs, `throw::ErrorPoint` and `throw::Error`. `throw::Error` stores a //! single `original_error` variable which it is created from, and then a list of `ErrorPoint`s //! which starts out with the original point of creation with `throw!()`, and is added to every //! time you propagate the error upwards with `up!()`. //! //! *Throw does not replace existing error handling systems*. The `throw::Error` type has a type //! parameter `E` which represents an internal error type stored. `throw::Error` just warps your //! error type and stores ErrorPoints alongside it. //! //! Throw helps you better keep track of your errors. Instead of seeing a generic "No such file or //! directory" message, you get a stack trace of functions which propagated the error as well. //! //! Instead of: //! //! ```text //! IO Error: failed to lookup address information: Name or service not known //! ``` //! //! Get: //! //! ```text //! Error: IO Error: failed to lookup address information: Name or service not known //! at 79:17 in zaldinar::startup (src/startup.rs) //! at 104:4 in zaldinar::startup (src/startup.rs) //! at 28:17 in zaldinar_irclib (/home/daboross/Projects/Rust/zaldinar/zaldinar-irclib/src/lib.rs) //! ``` //! //! --- //! //! Using throw! //! --- //! //! The main way you use throw is through two macros, `throw!()` and `up!()`. `throw!()` is used //! when you have a regular (non-throw) result coming from some library function that you want to //! propagate upwards in case of an error. `up!()` is used when you have an error which was //! created using `throw!()` in a sub-function which you want to add an error point to and //! propagate upwards. //! //! Here's an example of throw in action: //! //! ```rust //! #[macro_use] //! extern crate throw; //! //! use std::io::prelude::*; //! use std::io; //! use std::fs::File; //! //! fn read_log() -> Result<String, throw::Error<io::Error>> { //! let mut file = throw!(File::open("some_file.log")); //! let mut buf = String::new(); //! throw!(file.read_to_string(&mut buf)); //! Ok((buf)) //! } //! //! fn do_things() -> Result<(), throw::Error<io::Error>> { //! let log_contents = up!(read_log()); //! println!("Log contents: {}", log_contents); //! //! Ok(()) //! } //! //! fn main() { //! let result = do_things(); //! if let Err(e) = result { //! # /* //! panic!("{}", e); //! # */ //! # assert_eq!(format!("{}", e), "Error: No such file or directory (os error 2)\ //! # \n\tat 16:23 in rust_out (<anon>)\ //! # \n\tat 9:19 in rust_out (<anon>)"); //! } //! } //! ``` //! //! This simple program behaves exactly as if `Result<_, io::Error>` directly when it functions //! correctly. When the program encounters is when throw really shines. This will result in an //! error message: //! //! ```text //! Error: No such file or directory (os error 2) //! at 16:23 in main (src/main.rs) //! at 9:19 in main (src/main.rs) //! ``` //! //! These stack traces are stored inside throw::Error, and are recorded automatically when //! `throw!()` or `up!()` returns an Err value. //! //! In each `at` line, the `16:23` represents `line_num:column_num`, the `main` represents the //! module path (for example `my_program::sub_module`), and `src/main.rs` represents the path of //! the file in which `throw!()` was used in. //! //! --- //! //! Throwing directly from a function is also supported, using `throw_new!()`: //! //! ``` //! # #[macro_use] //! # extern crate throw; //! fn possibly_fails() -> Result<(), throw::Error<&'static str>> { //! if true { //! // throw_new!() will always return directly //! throw_new!("oops"); //! } //! //! Ok(()) //! } //! //! fn main() { //! # /* //! possibly_fails().unwrap() //! # */ //! # assert_eq!(format!("{}", possibly_fails().unwrap_err()), "Error: oops\ //! # \n\tat 6:8 in rust_out (<anon>)") //! } //! ``` //! //! ```text //! called `Result::unwrap()` on an `Err` value: Error: "oops" //! at 6:8 in main (src/main.rs) //! ``` //! //! `throw_new!()` differs from `throw!()` in that it takes a parameter directly to pass to a //! `throw::Error`, rather than a `Result<>` to match on. `throw_new!()` will always return //! directly from the function. use std::fmt; /// Result alias for a result containing a throw::Error. pub type Result<T, E> = std::result::Result<T, Error<E>>; /// Represents a location at which an error was thrown via throw!() pub struct ErrorPoint { line: u32, column: u32, module_path: &'static str, file: &'static str, } impl ErrorPoint { /// The line throw!() occurred at, retrieved by line!() #[inline] pub fn line(&self) -> u32 { self.line } /// The column throw!() occurred at, retrieved by column!() #[inline] pub fn column(&self) -> u32 { self.column } /// The module throw!() occurred in, retrieved by module_path!() #[inline] pub fn module_path(&self) -> &'static str { self.module_path } /// The file throw!() occurred in, retrieved by file!() #[inline] pub fn file(&self) -> &'static str { self.file } #[doc(hidden)] pub fn __construct(line: u32, column: u32, module_path: &'static str, file: &'static str) -> ErrorPoint { ErrorPoint { line: line, column: column, module_path: module_path, file: file, } } } /// Represents an error. Stores an original error of type E, and any number of ErrorPoints at /// which the error was propagated. pub struct Error<E> { points: Vec<ErrorPoint>, original_error: E, } impl<E> Error<E> { /// Creates a new Error with no ErrorPoints pub fn new(error: E) -> Error<E> { Error { points: Vec::new(), original_error: error, } } /// For macro use only #[doc(hidden)] pub fn __push_point(&mut self, point: ErrorPoint) { self.points.push(point); } /// Gets all ErrorPoints where this Error was thrown. These are in reverse order, with the /// first time it was thrown first and the latest time it was thrown last. #[inline] pub fn points(&self) -> &[ErrorPoint] { &self.points } /// Gets the original error which this Error was constructed with. #[inline] pub fn original_error(&self) -> &E { &self.original_error } /// Transforms this Error<OldError> into Error<NewError>. This isn't implemented as an Into or /// From implementation because it would conflict with the blanket implementations in stdlib. pub fn transform<NE>(self) -> Error<NE> where E: Into<NE> { Error { points: self.points, original_error: self.original_error.into(), } } } impl<E> fmt::Display for Error<E> where E: fmt::Display { fn fmt(&self, fmt: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { try!(write!(fmt, "Error: {}", self.original_error)); for point in self.points.iter().rev() { try!(write!(fmt, "\n\tat {}:{} in {} ({})", point.line(), point.column(), point.module_path(), point.file())); } Ok(()) } } impl<E> fmt::Debug for Error<E> where E: fmt::Debug { fn fmt(&self, fmt: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { try!(write!(fmt, "Error: {:?}", self.original_error)); for point in self.points.iter().rev() { try!(write!(fmt, "\n\tat {}:{} in {} ({})", point.line(), point.column(), point.module_path(), point.file())); } Ok(()) } } #[macro_export] macro_rules! up { ($e:expr) => ( match $e { Ok(v) => v, Err(e) => { // re-assignment for a better error message if up!() is used incorrectly let mut e: $crate::Error<_> = e.transform(); e.__push_point($crate::ErrorPoint::__construct( line!(), column!(), module_path!(), file!(), )); return Err(e); }, } ); } #[macro_export] macro_rules! throw { ($e:expr) => ( match $e { Ok(v) => v, Err(e) => throw_new!(e), } ); } #[macro_export] macro_rules! throw_new { ($e:expr) => ({ let mut e: $crate::Error<_> = $crate::Error::new($e.into()); e.__push_point($crate::ErrorPoint::__construct( line!(), column!(), module_path!(), file!(), )); return Err(e); }) }