Create specific error types with appropriate status codes while ensuring sensitive details are logged but not exposed to clients. Follow guidelines for defining specific error types, implementing proper status codes, logging detailed errors internally, and returning sanitized error messages to clients.
Create specific error types with appropriate status codes while ensuring sensitive details are logged but not exposed to clients. Follow these guidelines:
Example:
#[derive(Debug, Error)]
pub enum ApiError {
#[error("Invalid input provided")]
ValidationError(#[from] JsonRejection),
#[error("Internal server error")]
InternalError(#[source] anyhow::Error),
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = match &self {
Self::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
Self::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
// Log detailed error internally
tracing::error!("{:#}", self);
// Return sanitized response to client
let body = Json(json!({
"error": self.to_string() // Uses the #[error] messages
}));
(status, body).into_response()
}
}
Enter the URL of a public GitHub repository