use std::fmt;
use async_stream::stream;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use futures::Stream;
pub struct WebError {
status_code: StatusCode,
msg: String,
}
impl WebError {
pub fn new(status_code: StatusCode, msg: String) -> Self {
Self { status_code, msg }
}
pub fn new_string_stream(status_code: StatusCode, msg: String) -> impl Stream<Item = String> {
stream! {
yield format!("{}", Self::new(status_code, msg));
}
}
}
impl IntoResponse for WebError {
fn into_response(self) -> Response {
(self.status_code, self.msg).into_response()
}
}
impl From<anyhow::Error> for WebError {
fn from(err: anyhow::Error) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, format!("{:?}", err))
}
}
impl fmt::Display for WebError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, {}", self.status_code, self.msg)
}
}