Skip to content

Commit

Permalink
Rollup merge of rust-lang#91947 - ibraheemdev:io-error-other, r=josht…
Browse files Browse the repository at this point in the history
…riplett

Add `io::Error::other`

This PR adds a small utility constructor, `io::Error::other`, a shorthand for `io::Error::new(io::ErrorKind::Other, err)`, something I find myself writing often.

For some concrete stats, a quick search on [grep.app](https://grep.app) shows that more than half of the uses of `io::Error::new` use `ErrorKind::Other`:
```
Error::new\((?:std::)?(?:io::)?ErrorKind:: => 3,898 results
Error::new\((?:std::)?(?:io::)?ErrorKind::Other => 2,186 results
```
  • Loading branch information
matthiaskrgr authored Dec 16, 2021
2 parents 677caf3 + 85f786c commit 8cb6cc3
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions library/std/src/io/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,33 @@ impl Error {
Self::_new(kind, error.into())
}

/// Creates a new I/O error from an arbitrary error payload.
///
/// This function is used to generically create I/O errors which do not
/// originate from the OS itself. It is a shortcut for [`Error::new`]
/// with [`ErrorKind::Other`].
///
/// # Examples
///
/// ```
/// #![feature(io_error_other)]
///
/// use std::io::Error;
///
/// // errors can be created from strings
/// let custom_error = Error::other("oh no!");
///
/// // errors can also be created from other errors
/// let custom_error2 = Error::other(custom_error);
/// ```
#[unstable(feature = "io_error_other", issue = "91946")]
pub fn other<E>(error: E) -> Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
Self::_new(ErrorKind::Other, error.into())
}

fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
}
Expand Down

0 comments on commit 8cb6cc3

Please sign in to comment.