Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add shorthand way to return non-IntoResponse errors #3010

Merged
merged 16 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions axum-extra/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ default = ["tracing", "multipart"]

async-read-body = ["dep:tokio-util", "tokio-util?/io", "dep:tokio"]
attachment = ["dep:tracing"]
error_response = ["dep:tracing"]
jplatte marked this conversation as resolved.
Show resolved Hide resolved
cookie = ["dep:cookie"]
cookie-private = ["cookie", "cookie?/private"]
cookie-signed = ["cookie", "cookie?/signed"]
Expand Down
59 changes: 59 additions & 0 deletions axum-extra/src/response/error_response.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use axum_core::response::{IntoResponse, Response};
use http::StatusCode;
use std::error::Error;
use std::io::Write;
use tracing::error;

/// Convenience response to create an error response from a non-IntoResponse error
jplatte marked this conversation as resolved.
Show resolved Hide resolved
///
/// This provides a method to quickly respond with an error that does not implement
/// the IntoResponse trait itself. This type should only be used for debugging purposes or internal
jplatte marked this conversation as resolved.
Show resolved Hide resolved
/// facing applications, as it includes the full error chain with descriptions,
/// thus leaking information that could possibly be sensitive.
///
/// ```rust
/// use axum_extra::response::InternalServerError;
/// use axum_core::response::IntoResponse;
/// # use std::io::{Error, ErrorKind};
/// # fn try_thing() -> Result<(), Error> {
/// # Err(Error::new(ErrorKind::Other, "error"))
/// # }
///
/// async fn maybe_error() -> Result<String, InternalServerError<Error>> {
/// try_thing().map_err(InternalServerError)?;
/// // do something on success
/// # Ok(String::from("ok"))
/// }
/// ```
#[derive(Debug)]
pub struct InternalServerError<T>(pub T);

impl<T: Error> IntoResponse for InternalServerError<T> {
fn into_response(self) -> Response {
let mut body = Vec::new();
write!(body, "{}", self.0).unwrap();
let mut e: &dyn Error = &self.0;
while let Some(new_e) = e.source() {
e = new_e;
write!(body, ": {e}").unwrap();
}
error!("Internal server error: {}", body);
(
StatusCode::INTERNAL_SERVER_ERROR,
"An error occurred while processing your request.",
)
.into_response()
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::io::{Error, ErrorKind};

#[test]
fn internal_server_error() {
let response = InternalServerError(Error::new(ErrorKind::Other, "Test")).into_response();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}
6 changes: 6 additions & 0 deletions axum-extra/src/response/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ mod attachment;
#[cfg(feature = "multipart")]
pub mod multiple;

#[cfg(feature = "error_response")]
mod error_response;

#[cfg(feature = "error_response")]
pub use error_response::InternalServerError;

#[cfg(feature = "erased-json")]
pub use erased_json::ErasedJson;

Expand Down
Loading