Skip to content

Instantly share code, notes, and snippets.

@JSH32
Created March 6, 2022 01:28
Show Gist options
  • Save JSH32/52a3f0b472ca1c644bafb3e1c23e5628 to your computer and use it in GitHub Desktop.
Save JSH32/52a3f0b472ca1c644bafb3e1c23e5628 to your computer and use it in GitHub Desktop.
A response type for actix. Allows you to use `?` for every error
use derive_more::Display;
use thiserror::Error;
use actix_web::{http::StatusCode, HttpRequest, HttpResponse, Responder, ResponseError};
#[derive(Debug, Display)]
pub struct Error(anyhow::Error);
/// # Response
///
/// Utility type for error reporting.
///
/// The error variant accepts any error as it wraps [`anyhow::Error`].
/// This type should be returned from an Actix route handler.
/// Error variant should only be used when returning an exceptional case.
///
/// # Usage
/// ```
/// fn route() -> Response<()> {
/// Err(StringError("This could be any error type"))
/// }
/// ```
pub type Response<T> = Result<T, Error>;
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
log::error!("{}", &self.0.to_string());
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR, &self.0.to_string())
}
}
impl<E: Into<anyhow::Error>> From<E> for Error {
fn from(e: E) -> Self {
Self(e.into())
}
}
#[derive(Error, Debug)]
#[error("{0}")]
pub struct StringError(pub String);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment