diff --git a/src/bgzf/mod.rs b/src/bgzf/mod.rs index 06d6ee7a1..cc0a259fa 100644 --- a/src/bgzf/mod.rs +++ b/src/bgzf/mod.rs @@ -87,7 +87,13 @@ impl Reader { let mode = ffi::CString::new("r").unwrap(); let cpath = ffi::CString::new(path).unwrap(); let inner = unsafe { htslib::bgzf_open(cpath.as_ptr(), mode.as_ptr()) }; - Ok(Self { inner }) + if inner != std::ptr::null_mut() { + Ok(Self { inner }) + } else { + Err(Error::FileOpen { + path: String::from_utf8(path.to_vec()).unwrap(), + }) + } } /// Set the thread pool to use for parallel decompression. @@ -211,7 +217,13 @@ impl Writer { let mode = Self::get_open_mode(level)?; let cpath = ffi::CString::new(path).unwrap(); let inner = unsafe { htslib::bgzf_open(cpath.as_ptr(), mode.as_ptr()) }; - Ok(Self { inner, tpool: None }) + if inner != std::ptr::null_mut() { + Ok(Self { inner, tpool: None }) + } else { + Err(Error::FileOpen { + path: String::from_utf8(path.to_vec()).unwrap(), + }) + } } /// Internal function to convert compression level to "mode" diff --git a/src/errors.rs b/src/errors.rs index 2e89854f0..1fdc8f273 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -10,6 +10,8 @@ pub enum Error { // General errors #[error("file not found: {path}")] FileNotFound { path: PathBuf }, + #[error("file could not be opened: {path}")] + FileOpen { path: String }, #[error("invalid (non-unicode) characters in path")] NonUnicodePath, #[error("failed to fetch region")]