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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
//! A library for the construction of efficient static/dynamic single use error types per callsite. //! //! //! ```toml //! [dependencies] //! adhocerr = "0.1" //! ``` //! //! ## Examples //! //! Creating a root cause error: //! //! ```rust //! use adhocerr::err; //! # use std::{ //! # error::Error, //! # path::{Path, PathBuf}, //! # }; //! //! fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { //! start //! .ancestors() //! .find(|a| a.join(".git").is_dir()) //! .map(Path::to_owned) //! .ok_or(err!("Unable to find .git/ in parent directories")) //! } //! ``` //! //! Wrapping another Error: //! //! ```rust //! use adhocerr::wrap; //! # use std::error::Error; //! //! fn record_success() -> Result<(), impl Error + 'static> { //! std::fs::write(".success", "true").map_err(wrap!("Failed to save results of script")) //! } //! ``` //! //! ## Details //! //! This crate provides two primary macros. `err!` and `wrap!`. The former, `err!`, is used to //! create ad-hoc error types without a root cause from strings. `wrap!` on the other hand is used //! to create new errors with a source member. //! //! Both of these macros have two versions, and they generate completely different code, depending //! on whether or not string interopoation (`format!`-like code) is used in the error message. When //! the error message is a fixed string, the macro declares a new struct in line that has the //! string itself inserted into its `Display` implementation. This way no memory is used or //! allocations made to hold the error when they are not needed. //! //! For `err!` this means that your error type is a Zero Sized Type (ZST), for //! `wrap!` this means that your Wrapper error is the same size as the original //! error you're wrapping. //! //! When runtime interpolation is used and a `String` allocation is necessary it //! uses pre defined Error types to wrap the String to avoid declaring new types //! unnecessarily, but hides them behind an impl Trait boundary. //! //! ### Expanded //! //! The Expanded version of the example above would look like this: //! //! ```rust //! # use std::{ //! # error::Error, //! # path::{Path, PathBuf}, //! # }; //! fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { //! start //! .ancestors() //! .find(|a| a.join(".git").is_dir()) //! .map(Path::to_owned) //! .ok_or({ //! #[derive(Debug)] //! struct AdhocError; //! //! impl std::error::Error for AdhocError { //! fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { //! None //! } //! } //! //! impl core::fmt::Display for AdhocError { //! fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { //! f.write_str("Unable to find .git/ in parent directories") //! } //! } //! //! AdhocError //! }) //! } //! ``` use core::fmt; pub use err as format_err; /// Thinly wrap an error by defining a hidden error type and returning a closure to construct it /// /// ## Examples /// /// Wrap an error without changing its size or allocating: /// /// ```rust /// use adhocerr::wrap; /// # use std::error::Error; /// /// fn record_success() -> Result<(), impl Error + 'static> { /// std::fs::write(".success", "true").map_err(wrap!("Failed to save results of script")) /// } /// ``` /// /// Which expands to: /// /// /// ```rust /// # use std::error::Error; /// fn record_success() -> Result<(), impl Error + 'static> { /// std::fs::write(".success", "true").map_err({ /// #[derive(Debug)] /// struct WrappedError<E> { /// source: E, /// } /// /// impl<E> std::error::Error for WrappedError<E> /// where /// E: std::error::Error + 'static, /// { /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { /// Some(&self.source) /// } /// } /// /// impl<E> core::fmt::Display for WrappedError<E> /// where /// E: std::error::Error + 'static, /// { /// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { /// f.write_str("Failed to save results of script") /// } /// } /// /// |source| WrappedError { source } /// }) /// } /// ``` /// /// Wrapping an error with an runtime generated String: /// /// ```rust /// use adhocerr::wrap; /// # use std::{error::Error, path::Path}; /// /// fn record_success(file: &Path) -> Result<(), impl Error + 'static> { /// std::fs::write(file, "true").map_err(wrap!( /// "Failed to save results of script to file: {}", /// file.display() /// )) /// } /// ``` /// /// Which expands to: /// /// ```rust /// # use std::{error::Error, path::Path}; /// fn record_success(file: &Path) -> Result<(), impl Error + 'static> { /// std::fs::write(file, "true").map_err(|source| { /// adhocerr::private::format_wrap_err( /// source, /// format_args!( /// "Failed to save results of script to file: {}", /// file.display() /// ), /// ) /// }) /// } /// ``` #[macro_export] macro_rules! wrap { ($msg:literal) => {{ #[derive(Debug)] struct WrappedError<E> { source: E, } impl<E> std::error::Error for WrappedError<E> where E: std::error::Error + 'static, { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) } } impl<E> core::fmt::Display for WrappedError<E> where E: std::error::Error + 'static, { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str($msg) } } |source| WrappedError { source } }}; ($fmt:literal, $($arg:tt)*) => { |source| $crate::private::format_wrap_err(source, format_args!($fmt, $($arg)*)) }; } /// Create an ad-hoc error type with zero size if none is needed /// /// ## Examples /// /// Creating a static ad-hoc error type: /// /// ```rust /// use adhocerr::err; /// # use std::{ /// # error::Error, /// # path::{Path, PathBuf}, /// # }; /// /// fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { /// start /// .ancestors() /// .find(|a| a.join(".git").is_dir()) /// .map(Path::to_owned) /// .ok_or(err!("Unable to find .git/ in parent directories")) /// } /// ``` /// /// Which expands to: /// /// ```rust /// # use std::{ /// # error::Error, /// # path::{Path, PathBuf}, /// # }; /// fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { /// start /// .ancestors() /// .find(|a| a.join(".git").is_dir()) /// .map(Path::to_owned) /// .ok_or({ /// #[derive(Debug)] /// struct AdhocError; /// /// impl std::error::Error for AdhocError { /// fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { /// None /// } /// } /// /// impl core::fmt::Display for AdhocError { /// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { /// f.write_str("Unable to find .git/ in parent directories") /// } /// } /// /// AdhocError /// }) /// } /// ``` /// /// Creating a dynamic ad-hoc error type: /// /// ```rust /// use adhocerr::err; /// # use std::{ /// # error::Error, /// # path::{Path, PathBuf}, /// # }; /// /// fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { /// start /// .ancestors() /// .find(|a| a.join(".git").is_dir()) /// .map(Path::to_owned) /// .ok_or(err!( /// "Unable to find .git/ in parent directories for {}", /// start.display() /// )) /// } /// ``` /// /// Which expands to: /// /// ```rust /// # use std::{ /// # error::Error, /// # path::{Path, PathBuf}, /// # }; /// fn get_git_root(start: &Path) -> Result<PathBuf, impl Error + 'static> { /// start /// .ancestors() /// .find(|a| a.join(".git").is_dir()) /// .map(Path::to_owned) /// .ok_or(adhocerr::private::format_err(format_args!( /// "Unable to find .git/ in parent directories for {}", /// start.display() /// ))) /// } /// ``` #[macro_export] macro_rules! err { ($msg:literal) => {{ #[derive(Debug)] struct AdhocError; impl std::error::Error for AdhocError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } impl core::fmt::Display for AdhocError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str($msg) } } AdhocError }}; ($fmt:literal, $($arg:tt)*) => { $crate::private::format_err(format_args!($fmt, $($arg)*)) }; } #[derive(Debug)] struct FormatError(String); impl fmt::Display for FormatError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl std::error::Error for FormatError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } #[derive(Debug)] struct FormatWrappedError<E> { msg: String, source: E, } impl<E> fmt::Display for FormatWrappedError<E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.msg.fmt(f) } } impl<E> std::error::Error for FormatWrappedError<E> where E: std::error::Error + 'static, { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) } } /// Return early with an error if a condition is not satisfied. /// /// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`. /// /// Analogously to `assert!`, `ensure!` takes a condition and exits the function /// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error` /// rather than panicking. /// /// # Example /// /// ``` /// use adhocerr::ensure; /// /// fn main() -> Result<(), impl std::error::Error + 'static> { /// # let user = 0; /// # /// ensure!(user == 0, "only user 0 is allowed"); /// Ok(()) /// } /// ``` /// /// ``` /// use adhocerr::ensure; /// /// # const MAX_DEPTH: usize = 1; /// # /// fn main() -> Result<(), anyhow::Error> { /// # let depth = 0; /// # /// ensure!(depth <= MAX_DEPTH, "Recursion limit exceeded"?); /// Ok(()) /// } /// ``` #[macro_export] macro_rules! ensure { ($cond:expr, $msg:literal) => { if !$cond { return $crate::private::Err($crate::err!($msg)); } }; ($cond:expr, $msg:literal?) => { if !$cond { return $crate::private::Err($crate::err!($msg).into()); } }; ($cond:expr, $fmt:literal, $($arg:tt)*) => { if !$cond { return $crate::private::Err($crate::err!($fmt, $($arg)*)); } }; ($cond:expr, $fmt:literal, $($arg:tt)*?) => { if !$cond { return $crate::private::Err($crate::err!($fmt, $($arg)*).into()); } }; } /// Return an ad-hoc error immediately /// /// This macro is equivalent to `return Err(From::from($err))`. /// /// # Example /// /// ``` /// use adhocerr::bail; /// /// # fn has_permission(user: usize, resource: usize) -> bool { /// # true /// # } /// # /// fn main() -> Result<(), impl std::error::Error + 'static> { /// # let user = 0; /// # let resource = 0; /// # /// if !has_permission(user, resource) { /// bail!("permission denied for accessing {}", resource); /// } /// /// Ok(()) /// } /// ``` /// /// ``` /// use adhocerr::bail; /// /// # const MAX_DEPTH: usize = 1; /// # /// fn main() -> Result<(), anyhow::Error> { /// # let depth = 0; /// # /// if depth > MAX_DEPTH { /// bail!("Recursion limit exceeded"?); /// } /// /// Ok(()) /// } /// ``` #[macro_export] macro_rules! bail { ($msg:literal) => { return $crate::private::Err($crate::err!($msg)); }; ($msg:literal?) => { return $crate::private::Err($crate::err!($msg).into()); }; ($fmt:literal, $($arg:tt)*) => { return $crate::private::Err($crate::err!($fmt, $($arg)*)); }; ($fmt:literal, $($arg:tt)*?) => { return $crate::private::Err($crate::err!($fmt, $($arg)*).into()); }; } #[doc(hidden)] pub mod private { pub use core::result::Result::Err; pub fn format_err( args: core::fmt::Arguments<'_>, ) -> impl std::error::Error + Send + Sync + 'static { crate::FormatError(args.to_string()) } pub fn format_wrap_err( source: impl std::error::Error + Send + Sync + 'static, args: core::fmt::Arguments<'_>, ) -> impl std::error::Error + Send + Sync + 'static { crate::FormatWrappedError { msg: args.to_string(), source, } } } #[cfg(test)] mod tests { use super::*; fn try_code_anyhow() -> Result<(), anyhow::Error> { let code = 1; ensure!(code == 0, "Command exited with a non zero status code"?); Ok(()) } fn try_code_impl() -> Result<(), impl std::error::Error + 'static> { let code = 1; ensure!(code == 0, "Command exited with a non zero status code"); Ok(()) } #[test] #[should_panic] fn ensure_coerce() { try_code_anyhow().unwrap(); } #[test] #[should_panic] fn ensure_impl() { try_code_impl().unwrap(); } }