Skip to content

Commit f18a810

Browse files
author
John Doe
committed
refactor: Use thiserror to simplify error handling
1 parent 9bd9d47 commit f18a810

File tree

5 files changed

+44
-48
lines changed

5 files changed

+44
-48
lines changed

hakoniwa/src/child_process/error.rs

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
11
pub(crate) type Result<T> = std::result::Result<T, Error>;
22

3-
#[derive(Debug)]
4-
pub(crate) struct Error(pub String);
5-
6-
impl std::fmt::Display for Error {
7-
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8-
write!(f, "{}", self.0)
9-
}
10-
}
11-
12-
impl std::error::Error for Error {}
13-
14-
impl From<libseccomp::error::SeccompError> for Error {
15-
fn from(e: libseccomp::error::SeccompError) -> Self {
16-
Self(e.to_string())
17-
}
3+
#[derive(thiserror::Error, Debug)]
4+
pub(crate) enum Error {
5+
#[error(transparent)]
6+
SeccompError(#[from] libseccomp::error::SeccompError),
7+
#[error(transparent)]
8+
PathAbsError(#[from] path_abs::Error),
9+
#[error(transparent)]
10+
BincodeError(#[from] BincodeErrorKind),
11+
#[error("{0}")]
12+
SyscallError(String),
1813
}
1914

20-
impl From<path_abs::Error> for Error {
21-
fn from(e: path_abs::Error) -> Self {
22-
Self(e.to_string())
23-
}
15+
#[derive(thiserror::Error, Debug)]
16+
pub enum BincodeErrorKind {
17+
#[error(transparent)]
18+
EncodeError(#[from] bincode::error::EncodeError),
19+
#[error(transparent)]
20+
DecodeError(#[from] bincode::error::DecodeError),
2421
}

hakoniwa/src/child_process/result.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
44
use std::{os::unix::io::RawFd, time::Duration};
55

66
use crate::{
7-
child_process::{error::Error, error::Result, syscall},
7+
child_process::{error::*, syscall},
88
ExecutorResultStatus,
99
};
1010

@@ -40,7 +40,7 @@ impl ChildProcessResult {
4040
let config = config::standard();
4141
let encoded: Vec<u8> = match bincode::serde::encode_to_vec(cpr, config) {
4242
Ok(val) => val,
43-
Err(err) => return Err(Error(err.to_string())),
43+
Err(err) => return Err(Error::BincodeError(BincodeErrorKind::EncodeError(err))),
4444
};
4545
syscall::write(writer, encoded.as_slice()).map(|_| ())
4646
}
@@ -53,7 +53,7 @@ impl ChildProcessResult {
5353
let (decoded, _): (Self, usize) =
5454
match bincode::serde::decode_from_slice(&encoded[..], config) {
5555
Ok(val) => val,
56-
Err(err) => return Err(Error(err.to_string())),
56+
Err(err) => return Err(Error::BincodeError(BincodeErrorKind::DecodeError(err))),
5757
};
5858
Ok(decoded)
5959
}

hakoniwa/src/child_process/syscall.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ macro_rules! tryfn {
4747
$mod::$fn($($arg),*).map_err(|err| {
4848
let name = stringify!($fn);
4949
let args = format!($args_format, $($arg),*);
50-
Error(format!("{}({}) => {}", name, args, err))
50+
Error::SyscallError(format!("{}({}) => {}", name, args, err))
5151
})
5252
};
5353
}
@@ -59,14 +59,14 @@ pub(crate) fn metadata<P: AsRef<Path> + Debug>(path: P) -> Result<Metadata> {
5959
pub(crate) fn mkdir_p<P: AsRef<Path> + Debug>(path: P) -> Result<()> {
6060
fs::create_dir_all(path.as_ref()).map_err(|err| {
6161
let err = format!("mkdir_p({:?}) => {}", path.as_ref(), err);
62-
Error(err)
62+
Error::SyscallError(err)
6363
})
6464
}
6565

6666
pub(crate) fn rmdir<P: AsRef<Path> + Debug>(path: P) -> Result<()> {
6767
fs::remove_dir(path.as_ref()).map_err(|err| {
6868
let err = format!("rmdir({:?}) => {}", path.as_ref(), err);
69-
Error(err)
69+
Error::SyscallError(err)
7070
})
7171
}
7272

@@ -77,21 +77,21 @@ pub(crate) fn chdir<P: AsRef<Path> + Debug>(path: P) -> Result<()> {
7777
pub(crate) fn touch<P: AsRef<Path> + Debug>(path: P) -> Result<()> {
7878
File::create(path.as_ref()).map(|_| ()).map_err(|err| {
7979
let err = format!("touch({:?}) => {}", path.as_ref(), err);
80-
Error(err)
80+
Error::SyscallError(err)
8181
})
8282
}
8383

8484
pub(crate) fn read(fd: RawFd, buf: &mut [u8]) -> Result<usize> {
8585
unistd::read(fd, buf).map_err(|err| {
8686
let err = format!("read({:?}, ...) => {}", fd, err);
87-
Error(err)
87+
Error::SyscallError(err)
8888
})
8989
}
9090

9191
pub(crate) fn write(fd: RawFd, buf: &[u8]) -> Result<usize> {
9292
unistd::write(fd, buf).map_err(|err| {
9393
let err = format!("write({:?}, ...) => {}", fd, err);
94-
Error(err)
94+
Error::SyscallError(err)
9595
})
9696
}
9797

@@ -106,7 +106,7 @@ pub(crate) fn dup2(oldfd: RawFd, newfd: RawFd) -> Result<RawFd> {
106106
pub(crate) fn fwrite<P: AsRef<Path> + Debug>(path: P, content: &str) -> Result<()> {
107107
fs::write(path.as_ref(), content.as_bytes()).map_err(|err| {
108108
let err = format!("write({:?}, ...) => {}", path.as_ref(), err);
109-
Error(err)
109+
Error::SyscallError(err)
110110
})
111111
}
112112

@@ -155,7 +155,7 @@ pub(crate) fn unshare(clone_flags: CloneFlags) -> Result<()> {
155155
pub(crate) fn fork() -> Result<ForkResult> {
156156
unsafe { unistd::fork() }.map_err(|err| {
157157
let err = format!("fork() => {}", err);
158-
Error(err)
158+
Error::SyscallError(err)
159159
})
160160
}
161161

@@ -191,7 +191,7 @@ pub(crate) fn prctl_set_pdeathsig(sig: i32) -> Result<()> {
191191
let res = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, sig, 0, 0, 0) };
192192
if res == -1 {
193193
let err = format!("prctl(PR_SET_PDEATHSIG, {:?}, ...) => {}", sig, res);
194-
Err(Error(err))
194+
Err(Error::SyscallError(err))
195195
} else {
196196
Ok(())
197197
}
@@ -201,7 +201,7 @@ pub(crate) fn prctl_set_no_new_privs() -> Result<()> {
201201
let res = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
202202
if res == -1 {
203203
let err = format!("prctl(PR_SET_NO_NEW_PRIVS, ...) => {}", res);
204-
Err(Error(err))
204+
Err(Error::SyscallError(err))
205205
} else {
206206
Ok(())
207207
}
@@ -210,7 +210,7 @@ pub(crate) fn prctl_set_no_new_privs() -> Result<()> {
210210
pub(crate) fn sigaction(signal: Signal, sigaction: &SigAction) -> Result<SigAction> {
211211
unsafe { signal::sigaction(signal, sigaction) }.map_err(|err| {
212212
let err = format!("sigaction({:?}, ...) => {}", signal, err);
213-
Error(err)
213+
Error::SyscallError(err)
214214
})
215215
}
216216

hakoniwa/src/error.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ pub type Result<T> = std::result::Result<T, Error>;
22

33
#[derive(thiserror::Error, Debug)]
44
pub enum Error {
5-
#[error("{0}")]
6-
ParseConfigurationError(String),
5+
#[error(transparent)]
6+
ParseConfigurationError(#[from] ParseConfigurationErrorKind),
77
#[error("{0}: {1}")]
88
PathError(std::path::PathBuf, String),
99
#[error("seccomp: {0}")]
@@ -12,14 +12,10 @@ pub enum Error {
1212
_ExecutorRunError(String),
1313
}
1414

15-
impl From<handlebars::RenderError> for Error {
16-
fn from(e: handlebars::RenderError) -> Self {
17-
Self::ParseConfigurationError(e.to_string())
18-
}
19-
}
20-
21-
impl From<toml::de::Error> for Error {
22-
fn from(e: toml::de::Error) -> Self {
23-
Self::ParseConfigurationError(e.to_string())
24-
}
15+
#[derive(thiserror::Error, Debug)]
16+
pub enum ParseConfigurationErrorKind {
17+
#[error(transparent)]
18+
HandlebarsRenderError(#[from] handlebars::RenderError),
19+
#[error(transparent)]
20+
TomlError(#[from] toml::de::Error),
2521
}

hakoniwa/src/sandbox.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use std::{collections::HashMap, str};
55

66
use crate::{
77
contrib::handlebars::{fs_read_to_string_helper, os_env_helper, os_homedir_helper},
8-
Executor, File, Limits, Mount, Result, Seccomp,
8+
error, Executor, File, Limits, Mount, Result, Seccomp,
99
};
1010

1111
lazy_static! {
@@ -43,8 +43,11 @@ impl SandboxPolicy {
4343
/// Create a policy from a string.
4444
#[allow(clippy::should_implement_trait)]
4545
pub fn from_str(data: &str) -> Result<Self> {
46-
let data = SANDBOX_POLICY_HANDLEBARS.render_template(data, &())?;
47-
let policy: Self = toml::from_str(&data)?;
46+
let data = SANDBOX_POLICY_HANDLEBARS
47+
.render_template(data, &())
48+
.map_err(error::ParseConfigurationErrorKind::HandlebarsRenderError)?;
49+
let policy: Self =
50+
toml::from_str(&data).map_err(error::ParseConfigurationErrorKind::TomlError)?;
4851
Ok(policy)
4952
}
5053
}

0 commit comments

Comments
 (0)