Skip to content

Commit b742594

Browse files
authored
Rollup merge of rust-lang#91947 - ibraheemdev:io-error-other, r=joshtriplett
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 ```
2 parents 7e5c071 + 85f786c commit b742594

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

library/std/src/io/error.rs

+27
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,33 @@ impl Error {
417417
Self::_new(kind, error.into())
418418
}
419419

420+
/// Creates a new I/O error from an arbitrary error payload.
421+
///
422+
/// This function is used to generically create I/O errors which do not
423+
/// originate from the OS itself. It is a shortcut for [`Error::new`]
424+
/// with [`ErrorKind::Other`].
425+
///
426+
/// # Examples
427+
///
428+
/// ```
429+
/// #![feature(io_error_other)]
430+
///
431+
/// use std::io::Error;
432+
///
433+
/// // errors can be created from strings
434+
/// let custom_error = Error::other("oh no!");
435+
///
436+
/// // errors can also be created from other errors
437+
/// let custom_error2 = Error::other(custom_error);
438+
/// ```
439+
#[unstable(feature = "io_error_other", issue = "91946")]
440+
pub fn other<E>(error: E) -> Error
441+
where
442+
E: Into<Box<dyn error::Error + Send + Sync>>,
443+
{
444+
Self::_new(ErrorKind::Other, error.into())
445+
}
446+
420447
fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
421448
Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
422449
}

0 commit comments

Comments
 (0)