feat: handle JSON encoding errors as errors, without panic

They should never happens, but just in case.

Signed-off-by: Lars Wirzenius <liw@liw.fi>
This commit is contained in:
Lars Wirzenius
2024-07-29 13:48:13 +03:00
parent 2104c1a671
commit cf66efb550
2 changed files with 17 additions and 4 deletions
+11 -2
View File
@@ -91,8 +91,10 @@ struct ConfigCmd {
}
impl ConfigCmd {
fn run(&self, _args: &Args, config: &Config) -> Result<(), CibError> {
let json = config.to_json();
fn run(&self, args: &Args, config: &Config) -> Result<(), CibError> {
let json = config
.to_json()
.map_err(|e| CibError::to_json(&args.config, e))?;
if let Some(output) = &self.output {
write(output, json.as_bytes()).map_err(|e| CibError::write_config(output, e))?;
@@ -225,6 +227,9 @@ enum CibError {
#[error("failed to write config as JSON to file {0}")]
WriteConfig(PathBuf, #[source] std::io::Error),
#[error("failed to convert config as JSON")]
ToJson(PathBuf, #[source] ConfigError),
#[error("failed to look up node profile")]
Profile(#[source] radicle::profile::Error),
@@ -259,6 +264,10 @@ impl CibError {
Self::WriteConfig(filename.into(), e)
}
fn to_json(filename: &Path, e: ConfigError) -> Self {
Self::ToJson(filename.into(), e)
}
fn profile(e: radicle::profile::Error) -> Self {
Self::Profile(e)
}
+6 -2
View File
@@ -42,8 +42,8 @@ impl Config {
&self.db
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).expect("serialize config to JSON")
pub fn to_json(&self) -> Result<String, ConfigError> {
serde_json::to_string_pretty(self).map_err(ConfigError::ToJson)
}
}
@@ -88,4 +88,8 @@ pub enum ConfigError {
/// Can't parse config file as YAML.
#[error("failed to parse configuration file as YAML: {0}")]
ParseConfig(PathBuf, #[source] serde_yaml::Error),
/// Can't convert configuration into JSON.
#[error("failed to convert configuration into JSON")]
ToJson(#[source] serde_json::Error),
}