refactor: move error to separate module

This commit is contained in:
DarkCat09 2025-03-26 15:17:26 +04:00
parent 6b0bc1ed38
commit 4784c5a370
Signed by: DarkCat09
SSH key fingerprint: SHA256:SnH1iYY/ogxxRmt1I6piy+aVUUzrOWvfksQWfhZ8JUM
2 changed files with 48 additions and 40 deletions

39
src/error.rs Normal file
View file

@ -0,0 +1,39 @@
use std::{fmt, io, string::FromUtf8Error};
use ntex::{
http::StatusCode,
web::{HttpRequest, HttpResponse, WebResponseError},
};
#[derive(Debug)]
pub struct ErrorWrapper(io::Error);
impl From<io::Error> for ErrorWrapper {
#[inline]
fn from(value: io::Error) -> Self {
Self(value)
}
}
impl From<FromUtf8Error> for ErrorWrapper {
fn from(value: FromUtf8Error) -> Self {
Self(io::Error::new(io::ErrorKind::InvalidData, value))
}
}
impl fmt::Display for ErrorWrapper {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl WebResponseError for ErrorWrapper {
fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn error_response(&self, _: &HttpRequest) -> HttpResponse {
format!("{:?}", self.0).into()
}
}

View file

@ -2,10 +2,17 @@ use std::sync::Arc;
use ntex::{
http::StatusCode,
web::{self, App, HttpServer, Responder, WebResponseError, types::State},
web::{self, App, HttpServer, Responder, types::State},
};
type Result<T> = core::result::Result<T, ErrorWrapper>;
mod error;
type Result<T> = core::result::Result<T, error::ErrorWrapper>;
#[derive(Debug, Clone)]
struct Config {
doas: Option<Arc<String>>,
}
#[ntex::main]
async fn main() -> std::io::Result<()> {
@ -92,41 +99,3 @@ async fn temp(cfg: State<Config>) -> Result<impl Responder> {
Ok(String::from_utf8(out.stdout)?)
}
#[derive(Debug, Clone)]
struct Config {
doas: Option<Arc<String>>,
}
#[derive(Debug)]
struct ErrorWrapper(std::io::Error);
impl From<std::io::Error> for ErrorWrapper {
#[inline]
fn from(value: std::io::Error) -> Self {
Self(value)
}
}
impl From<std::string::FromUtf8Error> for ErrorWrapper {
fn from(value: std::string::FromUtf8Error) -> Self {
Self(std::io::Error::new(std::io::ErrorKind::InvalidData, value))
}
}
impl std::fmt::Display for ErrorWrapper {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl WebResponseError for ErrorWrapper {
fn status_code(&self) -> StatusCode {
StatusCode::INTERNAL_SERVER_ERROR
}
fn error_response(&self, _: &web::HttpRequest) -> web::HttpResponse {
format!("{:?}", self.0).into()
}
}