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

[Rust-Axum][Breaking Change] Implement a customizable error handler #20463

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,18 @@ struct ServerImpl {

#[allow(unused_variables)]
#[async_trait]
impl {{{packageName}}}::Api for ServerImpl {
impl {{{externCrateName}}}::apis::default::Api for ServerImpl {
// API implementation goes here
}

impl {{{externCrateName}}}::apis::ErrorHandler for ServerImpl {}

pub async fn start_server(addr: &str) {
// initialize tracing
tracing_subscriber::fmt::init();

// Init Axum router
let app = {{{packageName}}}::server::new(Arc::new(ServerImpl));
let app = {{{externCrateName}}}::server::new(Arc::new(ServerImpl));

// Add layers to the router
let app = app.layer(...);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,17 @@ pub trait ApiKeyAuthHeader {
}
{{/isKeyInHeader}}
{{/isApiKey}}
{{/authMethods}}
{{/authMethods}}

// Error handler for unhandled errors.
#[async_trait::async_trait]
pub trait ErrorHandler<E: std::fmt::Debug + Send + Sync + 'static = ()> {
#[tracing::instrument(skip(self))]
async fn handle_error(&self, error: E) -> Result<axum::response::Response, http::StatusCode> {
tracing::error!("Unhandled error: {:?}", error);
axum::response::Response::builder()
.status(500)
.body(axum::body::Body::empty())
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ use crate::{models, types::*};
/// {{classnamePascalCase}}
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait {{classnamePascalCase}} {
pub trait {{classnamePascalCase}}<E: std::fmt::Debug + Send + Sync + 'static = ()>: super::ErrorHandler<E> {
{{#havingAuthMethod}}
type Claims;
type Claims;

{{/havingAuthMethod}}
{{#operation}}
Expand Down Expand Up @@ -73,7 +73,7 @@ pub trait {{classnamePascalCase}} {
{{#x-consumes-multipart-related}}
body: axum::body::Body,
{{/x-consumes-multipart-related}}
) -> Result<{{{operationId}}}Response, ()>;
) -> Result<{{{operationId}}}Response, E>;
{{/vendorExtensions}}
{{^-last}}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}}
#[tracing::instrument(skip_all)]
async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A{{#havingAuthMethod}}, C{{/havingAuthMethod}}>(
async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A, E{{#havingAuthMethod}}, C{{/havingAuthMethod}}>(
method: Method,
host: Host,
cookies: CookieJar,
Expand Down Expand Up @@ -54,8 +54,9 @@ async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A{{#h
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: apis::{{classFilename}}::{{classnamePascalCase}}{{#havingAuthMethod}}<Claims = C>{{/havingAuthMethod}}{{#vendorExtensions}}{{#x-has-cookie-auth-methods}}+ apis::CookieAuthentication<Claims = C>{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}+ apis::ApiKeyAuthHeader<Claims = C>{{/x-has-header-auth-methods}}{{/vendorExtensions}},
{
A: apis::{{classFilename}}::{{classnamePascalCase}}<E{{#havingAuthMethod}}, Claims = C{{/havingAuthMethod}}>{{#vendorExtensions}}{{#x-has-cookie-auth-methods}}+ apis::CookieAuthentication<Claims = C>{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}+ apis::ApiKeyAuthHeader<Claims = C>{{/x-has-header-auth-methods}}{{/vendorExtensions}} + Send + Sync,
E: std::fmt::Debug + Send + Sync + 'static,
{
{{#vendorExtensions}}
{{#x-has-auth-methods}}
// Authentication
Expand Down Expand Up @@ -342,10 +343,10 @@ where
},
{{/responses}}
},
Err(_) => {
Err(why) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.status(500).body(Body::empty())
return api_impl.as_ref().handle_error(why).await;
},
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
/// Setup API Server.
pub fn new<I, A{{#havingAuthMethods}}, C{{/havingAuthMethods}}>(api_impl: I) -> Router
pub fn new<I, A, E{{#havingAuthMethods}}, C{{/havingAuthMethods}}>(api_impl: I) -> Router
where
I: AsRef<A> + Clone + Send + Sync + 'static,
A: {{#apiInfo}}{{#apis}}{{#operations}}apis::{{classFilename}}::{{classnamePascalCase}}{{#havingAuthMethod}}<Claims = C>{{/havingAuthMethod}} + {{/operations}}{{/apis}}{{/apiInfo}}{{#authMethods}}{{#isApiKey}}{{#isKeyInCookie}}apis::CookieAuthentication<Claims = C> + {{/isKeyInCookie}}{{#isKeyInHeader}}apis::ApiKeyAuthHeader<Claims = C> + {{/isKeyInHeader}}{{/isApiKey}}{{/authMethods}}'static,
A: {{#apiInfo}}{{#apis}}{{#operations}}apis::{{classFilename}}::{{classnamePascalCase}}<E{{#havingAuthMethod}}, Claims = C{{/havingAuthMethod}}> + {{/operations}}{{/apis}}{{/apiInfo}}{{#authMethods}}{{#isApiKey}}{{#isKeyInCookie}}apis::CookieAuthentication<Claims = C> + {{/isKeyInCookie}}{{#isKeyInHeader}}apis::ApiKeyAuthHeader<Claims = C> + {{/isKeyInHeader}}{{/isApiKey}}{{/authMethods}}Send + Sync + 'static,
E: std::fmt::Debug + Send + Sync + 'static,
{{#havingAuthMethods}}C: Send + Sync + 'static,{{/havingAuthMethods}}
{
// build our application with a route
Router::new()
{{#pathMethodOps}}
.route("{{{basePathWithoutHost}}}{{{path}}}",
{{#methodOperations}}{{{method}}}({{{operationID}}}::<I, A{{#vendorExtensions}}{{#havingAuthMethod}}, C{{/havingAuthMethod}}{{/vendorExtensions}}>){{^-last}}.{{/-last}}{{/methodOperations}}
{{#methodOperations}}{{{method}}}({{{operationID}}}::<I, A, E{{#vendorExtensions}}{{#havingAuthMethod}}, C{{/havingAuthMethod}}{{/vendorExtensions}}>){{^-last}}.{{/-last}}{{/methodOperations}}
)
{{/pathMethodOps}}
.with_state(api_impl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,18 @@ struct ServerImpl {

#[allow(unused_variables)]
#[async_trait]
impl apikey-auths::Api for ServerImpl {
impl apikey_auths::apis::default::Api for ServerImpl {
// API implementation goes here
}

impl apikey_auths::apis::ErrorHandler for ServerImpl {}

pub async fn start_server(addr: &str) {
// initialize tracing
tracing_subscriber::fmt::init();

// Init Axum router
let app = apikey-auths::server::new(Arc::new(ServerImpl));
let app = apikey_auths::server::new(Arc::new(ServerImpl));

// Add layers to the router
let app = app.layer(...);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,16 @@ pub trait CookieAuthentication {
key: &str,
) -> Option<Self::Claims>;
}

// Error handler for unhandled errors.
#[async_trait::async_trait]
pub trait ErrorHandler<E: std::fmt::Debug + Send + Sync + 'static = ()> {
#[tracing::instrument(skip(self))]
async fn handle_error(&self, error: E) -> Result<axum::response::Response, http::StatusCode> {
tracing::error!("Unhandled error: {:?}", error);
axum::response::Response::builder()
.status(500)
.body(axum::body::Body::empty())
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ pub enum PostMakePaymentResponse {
/// Payments
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait Payments {
pub trait Payments<E: std::fmt::Debug + Send + Sync + 'static = ()>:
super::ErrorHandler<E>
{
type Claims;

/// Get payment method by id.
Expand All @@ -50,7 +52,7 @@ pub trait Payments {
host: Host,
cookies: CookieJar,
path_params: models::GetPaymentMethodByIdPathParams,
) -> Result<GetPaymentMethodByIdResponse, ()>;
) -> Result<GetPaymentMethodByIdResponse, E>;

/// Get payment methods.
///
Expand All @@ -60,7 +62,7 @@ pub trait Payments {
method: Method,
host: Host,
cookies: CookieJar,
) -> Result<GetPaymentMethodsResponse, ()>;
) -> Result<GetPaymentMethodsResponse, E>;

/// Make a payment.
///
Expand All @@ -72,5 +74,5 @@ pub trait Payments {
cookies: CookieJar,
claims: Self::Claims,
body: Option<models::Payment>,
) -> Result<PostMakePaymentResponse, ()>;
) -> Result<PostMakePaymentResponse, E>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,29 @@ use crate::{header, types::*};
use crate::{apis, models};

/// Setup API Server.
pub fn new<I, A, C>(api_impl: I) -> Router
pub fn new<I, A, E, C>(api_impl: I) -> Router
where
I: AsRef<A> + Clone + Send + Sync + 'static,
A: apis::payments::Payments<Claims = C>
A: apis::payments::Payments<E, Claims = C>
+ apis::ApiKeyAuthHeader<Claims = C>
+ apis::CookieAuthentication<Claims = C>
+ Send
+ Sync
+ 'static,
E: std::fmt::Debug + Send + Sync + 'static,
C: Send + Sync + 'static,
{
// build our application with a route
Router::new()
.route("/v71/paymentMethods", get(get_payment_methods::<I, A, C>))
.route(
"/v71/paymentMethods",
get(get_payment_methods::<I, A, E, C>),
)
.route(
"/v71/paymentMethods/:id",
get(get_payment_method_by_id::<I, A, C>),
get(get_payment_method_by_id::<I, A, E, C>),
)
.route("/v71/payments", post(post_make_payment::<I, A, C>))
.route("/v71/payments", post(post_make_payment::<I, A, E, C>))
.with_state(api_impl)
}

Expand All @@ -43,7 +49,7 @@ fn get_payment_method_by_id_validation(
}
/// GetPaymentMethodById - GET /v71/paymentMethods/{id}
#[tracing::instrument(skip_all)]
async fn get_payment_method_by_id<I, A, C>(
async fn get_payment_method_by_id<I, A, E, C>(
method: Method,
host: Host,
cookies: CookieJar,
Expand All @@ -52,7 +58,8 @@ async fn get_payment_method_by_id<I, A, C>(
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: apis::payments::Payments<Claims = C>,
A: apis::payments::Payments<E, Claims = C> + Send + Sync,
E: std::fmt::Debug + Send + Sync + 'static,
{
#[allow(clippy::redundant_closure)]
let validation =
Expand Down Expand Up @@ -123,10 +130,10 @@ where
response.body(Body::from(body_content))
}
},
Err(_) => {
Err(why) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.status(500).body(Body::empty())
return api_impl.as_ref().handle_error(why).await;
}
};

Expand All @@ -142,15 +149,16 @@ fn get_payment_methods_validation() -> std::result::Result<(), ValidationErrors>
}
/// GetPaymentMethods - GET /v71/paymentMethods
#[tracing::instrument(skip_all)]
async fn get_payment_methods<I, A, C>(
async fn get_payment_methods<I, A, E, C>(
method: Method,
host: Host,
cookies: CookieJar,
State(api_impl): State<I>,
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: apis::payments::Payments<Claims = C>,
A: apis::payments::Payments<E, Claims = C> + Send + Sync,
E: std::fmt::Debug + Send + Sync + 'static,
{
#[allow(clippy::redundant_closure)]
let validation = tokio::task::spawn_blocking(move || get_payment_methods_validation())
Expand Down Expand Up @@ -197,10 +205,10 @@ where
response.body(Body::from(body_content))
}
},
Err(_) => {
Err(why) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.status(500).body(Body::empty())
return api_impl.as_ref().handle_error(why).await;
}
};

Expand Down Expand Up @@ -230,7 +238,7 @@ fn post_make_payment_validation(
}
/// PostMakePayment - POST /v71/payments
#[tracing::instrument(skip_all)]
async fn post_make_payment<I, A, C>(
async fn post_make_payment<I, A, E, C>(
method: Method,
host: Host,
cookies: CookieJar,
Expand All @@ -239,7 +247,11 @@ async fn post_make_payment<I, A, C>(
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: apis::payments::Payments<Claims = C> + apis::CookieAuthentication<Claims = C>,
A: apis::payments::Payments<E, Claims = C>
+ apis::CookieAuthentication<Claims = C>
+ Send
+ Sync,
E: std::fmt::Debug + Send + Sync + 'static,
{
// Authentication
let claims_in_cookie = api_impl
Expand Down Expand Up @@ -322,10 +334,10 @@ where
response.body(Body::from(body_content))
}
},
Err(_) => {
Err(why) => {
// Application code returned an error. This should not happen, as the implementation should
// return a valid response.
response.status(500).body(Body::empty())
return api_impl.as_ref().handle_error(why).await;
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,18 @@ struct ServerImpl {

#[allow(unused_variables)]
#[async_trait]
impl multipart-v3::Api for ServerImpl {
impl multipart_v3::apis::default::Api for ServerImpl {
// API implementation goes here
}

impl multipart_v3::apis::ErrorHandler for ServerImpl {}

pub async fn start_server(addr: &str) {
// initialize tracing
tracing_subscriber::fmt::init();

// Init Axum router
let app = multipart-v3::server::new(Arc::new(ServerImpl));
let app = multipart_v3::server::new(Arc::new(ServerImpl));

// Add layers to the router
let app = app.layer(...);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,15 @@ pub enum MultipleIdenticalMimeTypesPostResponse {
/// Default
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait Default {
pub trait Default<E: std::fmt::Debug + Send + Sync + 'static = ()>: super::ErrorHandler<E> {
/// MultipartRelatedRequestPost - POST /multipart_related_request
async fn multipart_related_request_post(
&self,
method: Method,
host: Host,
cookies: CookieJar,
body: axum::body::Body,
) -> Result<MultipartRelatedRequestPostResponse, ()>;
) -> Result<MultipartRelatedRequestPostResponse, E>;

/// MultipartRequestPost - POST /multipart_request
async fn multipart_request_post(
Expand All @@ -51,7 +51,7 @@ pub trait Default {
host: Host,
cookies: CookieJar,
body: Multipart,
) -> Result<MultipartRequestPostResponse, ()>;
) -> Result<MultipartRequestPostResponse, E>;

/// MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types
async fn multiple_identical_mime_types_post(
Expand All @@ -60,5 +60,5 @@ pub trait Default {
host: Host,
cookies: CookieJar,
body: axum::body::Body,
) -> Result<MultipleIdenticalMimeTypesPostResponse, ()>;
) -> Result<MultipleIdenticalMimeTypesPostResponse, E>;
}
Original file line number Diff line number Diff line change
@@ -1 +1,14 @@
pub mod default;

// Error handler for unhandled errors.
#[async_trait::async_trait]
pub trait ErrorHandler<E: std::fmt::Debug + Send + Sync + 'static = ()> {
#[tracing::instrument(skip(self))]
async fn handle_error(&self, error: E) -> Result<axum::response::Response, http::StatusCode> {
tracing::error!("Unhandled error: {:?}", error);
axum::response::Response::builder()
.status(500)
.body(axum::body::Body::empty())
.map_err(|_| http::StatusCode::INTERNAL_SERVER_ERROR)
}
}
Loading
Loading