feat: improve error message

when init config failed:

```
Error: init config failed

Caused by:
    0: internal server error read ./config.toml failed
    1: read ./config.toml failed
    2: No such file or directory (os error 2)
```
This commit is contained in:
xfy
2024-05-12 17:44:34 +08:00
parent 2ffc081414
commit 8d48a2c34e
3 changed files with 6 additions and 8 deletions

View File

@ -7,6 +7,7 @@ use crate::{
};
use std::{collections::BTreeMap, fs};
use anyhow::Context;
use serde::Deserialize;
#[derive(Deserialize, Clone, Debug)]
@ -47,7 +48,7 @@ pub struct Settings {
}
pub fn init_config() -> Result<Settings> {
let file = fs::read_to_string("./config.toml")?;
let file = fs::read_to_string("./config.toml").with_context(|| "read ./config.toml failed")?;
let mut settings: Settings = toml::from_str(&file)?;
// convert route map

View File

@ -1,6 +1,5 @@
use std::{collections::BTreeMap, env, process::exit, sync::OnceLock};
use anyhow::Context;
use tracing::error;
use crate::config::{init_config, Settings};
@ -10,12 +9,8 @@ static SETTINGS: OnceLock<Settings> = OnceLock::new();
pub fn get_settings() -> &'static Settings {
SETTINGS.get_or_init(|| {
init_config()
.with_context(|| "init config failed")
.map_err(|err| {
error!("{err}");
if let Some(err) = err.source() {
error!("cause by {:?}", err)
}
error!("get_or_init config failed: {err}");
exit(1);
})
.unwrap()

View File

@ -1,9 +1,10 @@
use anyhow::Result;
use anyhow::{Context, Result};
use tokio::task::JoinSet;
use tracing::{debug, info};
use crate::{
config::init_config,
consts::{get_settings, ARCH, NAME, OS, VERSION},
utils::init_logger,
};
@ -18,6 +19,7 @@ mod utils;
#[tokio::main]
async fn main() -> Result<()> {
init_logger();
init_config().with_context(|| "init config failed")?;
// global config
let settings = get_settings();