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
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://wisagan.github.io/simple-error/simple_error/")]
#![deny(missing_docs)]
//! A simple error type backed by a string.
//!
//! This crate provides a `SimpleError` type, which implements `std::error::Error`. The underlying
//! is a `String` as the error message.
//!
//! It should be used when all you care about is an error string.
//!
//! It should not be used when you want to programmatically handle different kinds of an error.
use std::fmt;
/// A type that represents a simple error.
///
/// This type uses a `String` to store the error string, and it implements `std::error::Error`.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SimpleError {
err: String,
}
impl SimpleError {
/// Creates a new simple error.
///
/// This function can take any type that implements `Into<String>`.
///
/// # Examples
///
/// ```
/// use self::simple_error::SimpleError;
///
/// // errors can be created from `str`
/// let err = SimpleError::new("an error from str");
///
/// // errors can also be created from `String`
/// let err = SimpleError::new(String::from("an error from String"));
/// ```
#[inline]
pub fn new<T: Into<String>>(t: T) -> SimpleError {
SimpleError{ err: t.into() }
}
/// Creates a new simple error from another error.
///
/// This function can take any type that implements `std::error::Error`.
/// The error string will be the `Display` of the `std::error::Error`.
///
/// # Examples
///
/// ```
/// use self::simple_error::SimpleError;
/// use std::io;
///
/// // errors can be created from `io::Error`
/// let err = SimpleError::from(io::Error::new(io::ErrorKind::Other, "oh no"));
/// assert_eq!("oh no", format!("{}", err));
/// ```
#[inline]
pub fn from<T: std::error::Error>(t: T) -> SimpleError {
SimpleError{ err: format!("{t}") }
}
/// Creates a new simple error from a string with another error.
///
/// This function takes a string as error and a type that implements `std::error::Error` as
/// reason.
/// The error string will be the `Display` of the `std::error::Error` prefixed with the string
/// and ", ".
///
/// # Examples
///
/// ```
/// use self::simple_error::SimpleError;
///
/// let err = SimpleError::with("cannot turn on tv", SimpleError::new("remote not found"));
/// assert_eq!("cannot turn on tv, remote not found", format!("{}", err));
/// ```
#[inline]
pub fn with<T: std::error::Error>(s: &str, t: T) -> SimpleError {
SimpleError{ err: format!("{s}, {t}") }
}
/// Extracts a string slice describing the error.
///
/// # Examples
///
/// ```
/// use self::simple_error::SimpleError;
///
/// let s = SimpleError::new("critical error");
/// assert_eq!("critical error", s.as_str());
/// ```
#[inline]
pub fn as_str(&self) -> &str {
&self.err
}
}
// TODO: implement From<T> where T: std::error::Error when specialization lands, and remove
// inherent from function.
impl<'a> From<&'a str> for SimpleError {
#[inline]
fn from(s: &str) -> SimpleError {
SimpleError{ err: s.into() }
}
}
impl fmt::Display for SimpleError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.err.fmt(f)
}
}
impl std::error::Error for SimpleError {
}
/// Result type in which the error is a simple error
pub type SimpleResult<T> = Result<T, SimpleError>;
/// Helper macro for unwrapping `Result` values while returning early with a
/// newly constructed `SimpleError` if the value of the expression is `Err`.
/// Can only be used in functions that return `Result<_, SimpleError>`.
///
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate simple_error;
/// # fn main() {
/// use self::simple_error::SimpleError;
/// use std::error::Error;
///
/// fn try_block(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
/// Ok(try_with!(result, s))
/// }
///
/// // Above is equivalent to below.
///
/// fn try_block_equivalent(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
/// match result {
/// Ok(v) => Ok(v),
/// Err(e) => {
/// return Err(SimpleError::with(s, e));
/// },
/// }
/// }
///
/// // Use a format string
///
/// fn try_block_format(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
/// Ok(try_with!(result, "with {}", s))
/// }
///
/// // Use a format string to a boxed error
///
/// fn try_block_format_to_box_error(result: Result<(), SimpleError>, s: &str) -> Result<(), Box<dyn Error>> {
/// Ok(try_with!(result, "with {}", s))
/// }
/// # }
/// ```
#[macro_export]
macro_rules! try_with {
($expr: expr, $fmt:literal) => (match $expr {
Ok(val) => val,
Err(err) => {
return Err(::std::convert::From::from($crate::SimpleError::with(&format!($fmt), err)));
},
});
($expr: expr, $str: expr) => (match $expr {
Ok(val) => val,
Err(err) => {
return Err(::std::convert::From::from($crate::SimpleError::with($str.as_ref(), err)));
},
});
($expr: expr, $fmt:literal, $($arg:tt)+) => (match $expr {
Ok(val) => val,
Err(err) => {
return Err(::std::convert::From::from($crate::SimpleError::with(&format!($fmt, $($arg)+), err)));
},
});
}
/// Helper macro for unwrapping `Option` values while returning early with a
/// newly constructed `SimpleError` if the value of the expression is `None`.
/// Can only be used in functions that return `Result<_, SimpleError>`.
///
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate simple_error;
/// # fn main() {
/// use self::simple_error::SimpleError;
/// use std::error::Error;
///
/// fn require_block(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
/// Ok(require_with!(maybe, s))
/// }
///
/// // Above is equivalent to below.
///
/// fn require_block_equivalent(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
/// match maybe {
/// Some(v) => Ok(v),
/// None => {
/// return Err(SimpleError::new(s));
/// },
/// }
/// }
///
/// // Use a format string
///
/// fn require_block_format(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
/// Ok(require_with!(maybe, "with {}", s))
/// }
///
/// // Use a format string to a boxed error
///
/// fn require_block_format_to_box_error(maybe: Option<()>, s: &str) -> Result<(), Box<dyn Error>> {
/// Ok(require_with!(maybe, "with {}", s))
/// }
/// # }
/// ```
#[macro_export]
macro_rules! require_with {
($expr: expr, $fmt:literal) => (match $expr {
Some(val) => val,
None => {
return Err(::std::convert::From::from($crate::SimpleError::new(format!($fmt))));
},
});
($expr: expr, $str: expr) => (match $expr {
Some(val) => val,
None => {
return Err(::std::convert::From::from($crate::SimpleError::new(::std::convert::AsRef::<str>::as_ref($str))));
},
});
($expr: expr, $fmt:literal, $($arg:tt)+) => (match $expr {
Some(val) => val,
None => {
return Err(::std::convert::From::from($crate::SimpleError::new(format!($fmt, $($arg)+))));
},
});
}
/// Helper macro for returning a `SimpleError` constructed from either a `Into<SimpleError>`, a
/// string slice, or a formatted string.
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate simple_error;
/// # fn main() {
/// use self::simple_error::SimpleError;
/// use std::error::Error;
/// // Use with a `Into<SimpleError>`
///
/// struct ErrorSeed;
///
/// impl From<ErrorSeed> for SimpleError {
/// fn from(_: ErrorSeed) -> SimpleError {
/// SimpleError::new(".")
/// }
/// }
///
/// fn bail_block_into(es: ErrorSeed) -> Result<(), SimpleError> {
/// bail!(es);
/// }
///
/// // Use with a string slice
/// fn bail_block_str(s: &str) -> Result<(), SimpleError> {
/// bail!(s);
/// }
///
/// // Use with a formatted string
/// fn bail_block_format(s: &str) -> Result<(), SimpleError> {
/// bail!("reason: {}", s);
/// }
///
/// // Use with a formatted string to a boxed error
/// fn bail_block_format_to_box_error(s: &str) -> Result<(), Box<dyn Error>> {
/// bail!("reason: {}", s);
/// }
/// # }
/// ```
#[macro_export]
macro_rules! bail {
($fmt:literal) => {
return Err(::std::convert::From::from($crate::SimpleError::new(format!($fmt))));
};
($e:expr) => {
return Err(::std::convert::From::from($e));
};
($fmt:literal, $($arg:tt)+) => {
return Err(::std::convert::From::from($crate::SimpleError::new(format!($fmt, $($arg)+))));
};
}
/// Construct an ad-hoc `SimpleError` from a string.
///
/// It can take either just a string, or a format string with arguments.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate simple_error;
/// # fn main() {
/// use self::simple_error::SimpleResult;
///
/// fn add_reason(r: Result<(), ()>) -> SimpleResult<()> {
/// // Use with a string slice
/// r.map_err(|_| simple_error!("no reason"))
/// }
///
/// fn add_reason_with_str(r: Result<(), ()>, s: &str) -> SimpleResult<()> {
/// // Use with a formatted string
/// r.map_err(|_| simple_error!("reason: {}", s))
/// }
/// # }
/// ```
#[macro_export]
macro_rules! simple_error {
($fmt:literal) => {
$crate::SimpleError::new(format!($fmt))
};
($e:expr) => {
$crate::SimpleError::new($e)
};
($fmt:literal, $($arg:tt)+) => {
$crate::SimpleError::new(format!($fmt, $($arg)+))
};
}
/// Map a result type error to simple error with format
///
/// It can take either just a string, or a format string with arguments.
///
/// # Example
///
/// ```
/// # #[macro_use] extern crate simple_error;
/// # fn main() {
/// use self::simple_error::SimpleResult;
///
/// fn map_err_with_reason(r: Result<(), std::io::Error>) -> SimpleResult<()> {
/// // Use with a string slice
/// map_err_with!(r, "no reason")
/// }
///
/// fn map_err_with_reason_with_str(r: Result<(), std::io::Error>, s: &str) -> SimpleResult<()> {
/// // Use with a formatted string
/// map_err_with!(r, "no reason: {}", s)
/// }
/// # }
/// ```
#[macro_export]
macro_rules! map_err_with {
($r: expr, $fmt:literal) => {
$r.map_err(|e| $crate::SimpleError::with(&format!($fmt), e))
};
($r: expr, $str: expr) => {
$r.map_err(|e| $crate::SimpleError::with($str.as_ref(), e))
};
($r: expr, $fmt:literal, $($arg:tt)+) => {
$r.map_err(|e| $crate::SimpleError::with(&format!($fmt, $($arg)+), e))
};
}
#[cfg(test)]
mod tests {
use super::SimpleError;
use std::error::Error;
use std::io;
pub struct ErrorSeed;
impl From<ErrorSeed> for SimpleError {
fn from(_: ErrorSeed) -> SimpleError {
SimpleError::new(".")
}
}
#[test]
fn new_from_string() {
let err = SimpleError::new(String::from("an error from String"));
assert_eq!("an error from String", format!("{err}"));
}
#[test]
fn new_from_str() {
let err = SimpleError::new("an error from str");
assert_eq!("an error from str", format!("{err}"));
}
#[test]
fn new_from_simple_error_macro() {
let err = SimpleError::new("an error from str");
assert_eq!(SimpleError::new("an error from str"), simple_error!("{err}"));
}
#[test]
fn map_error_with_macro() {
let err = crate::SimpleResult::<()>::Err(SimpleError::new("an error from str"));
let additional_reason = "error in current function";
assert_eq!(Err(SimpleError::new("error in current function, an error from str")), map_err_with!(err, "{additional_reason}"));
}
#[test]
fn from_io_error() {
let err = SimpleError::from(io::Error::new(io::ErrorKind::Other, "oh no"));
assert_eq!("oh no", format!("{err}"));
}
fn try_block(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
Ok(try_with!(result, s))
}
fn try_block_format(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
Ok(try_with!(result, "with {}", s))
}
fn try_block_format_with_capture(result: Result<(), SimpleError>, s: &str) -> Result<(), SimpleError> {
Ok(try_with!(result, "with {s}"))
}
#[test]
fn macro_try_with() {
assert_eq!(Ok(()), try_block(Ok(()), ""));
assert_eq!(Err(SimpleError::new("try block error, error foo")), try_block(Err(SimpleError::new("error foo")), "try block error"));
assert_eq!(Err(SimpleError::new("with try block error, error foo")), try_block_format(Err(SimpleError::new("error foo")), "try block error"));
assert_eq!(Err(SimpleError::new("with try block error, error foo")), try_block_format_with_capture(Err(SimpleError::new("error foo")), "try block error"));
}
fn require_block(option: Option<()>, s: &str) -> Result<(), SimpleError> {
Ok(require_with!(option, s))
}
fn require_block_str_as_ref(option: Option<()>, s: &String) -> Result<(), SimpleError> {
Ok(require_with!(option, s))
}
fn require_block_format(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
Ok(require_with!(maybe, "with {}", s))
}
fn require_block_format_with_capture(maybe: Option<()>, s: &str) -> Result<(), SimpleError> {
Ok(require_with!(maybe, "with {s}"))
}
#[test]
fn macro_require_with() {
assert_eq!(Ok(()), require_block(Some(()), ""));
assert_eq!(Err(SimpleError::new("require block error")), require_block(None, "require block error"));
assert_eq!(Err(SimpleError::new("require block error")), require_block_str_as_ref(None, &"require block error".to_owned()));
assert_eq!(Err(SimpleError::new("with require block error")), require_block_format(None, "require block error"));
assert_eq!(Err(SimpleError::new("with require block error")), require_block_format_with_capture(None, "require block error"));
}
fn bail_block_into(es: ErrorSeed) -> Result<(), SimpleError> {
bail!(es);
}
fn bail_block_str(s: &str) -> Result<(), SimpleError> {
bail!(s);
}
fn bail_block_format(s: &str) -> Result<(), SimpleError> {
bail!("reason: {}", s);
}
fn bail_block_format_with_capture(s: &str) -> Result<(), SimpleError> {
bail!("reason: {s}");
}
fn bail_block_format_to_box_error(s: &str) -> Result<(), Box<dyn Error>> {
bail!("reason: {}", s);
}
#[test]
fn macro_bail() {
assert_eq!(Err(SimpleError::new(".")), bail_block_into(ErrorSeed));
assert_eq!(Err(SimpleError::new("no reason")), bail_block_str("no reason"));
assert_eq!(Err(SimpleError::new("reason: plane crashed")), bail_block_format("plane crashed"));
assert!(bail_block_format_to_box_error("plane crashed").is_err());
}
#[test]
fn inline_format_arg_capture() {
assert_eq!(Err(SimpleError::new("reason: plane crashed")), bail_block_format_with_capture("plane crashed"));
}
}