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

Merged
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ tokio = { version = "1", default-features = false, features = [
] }
tracing = { version = "0.1", features = ["attributes"] }
uuid = { version = "1", features = ["serde"] }
validator = { version = "0.19", features = ["derive"] }
validator = { version = "0.20", features = ["derive"] }

[dev-dependencies]
tracing-subscriber = "0.3"
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,24 @@ 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 = ()> {
#[allow(unused_variables)]
#[tracing::instrument(skip_all)]
async fn handle_error(
&self,
method: &::http::Method,
host: &axum::extract::Host,
cookies: &axum_extra::extract::CookieJar,
error: E
) -> Result<axum::response::Response, http::StatusCode> {
tracing::error!("Unhandled error: {:?}", error);
axum::response::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.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 All @@ -31,49 +31,49 @@ pub trait {{classnamePascalCase}} {
/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}}
async fn {{{x-operation-id}}}(
&self,
method: Method,
host: Host,
cookies: CookieJar,
method: &Method,
host: &Host,
cookies: &CookieJar,
{{#vendorExtensions}}
{{#x-has-auth-methods}}
claims: Self::Claims,
claims: &Self::Claims,
{{/x-has-auth-methods}}
{{/vendorExtensions}}
{{#headerParams.size}}
header_params: models::{{{operationIdCamelCase}}}HeaderParams,
header_params: &models::{{{operationIdCamelCase}}}HeaderParams,
{{/headerParams.size}}
{{#pathParams.size}}
path_params: models::{{{operationIdCamelCase}}}PathParams,
path_params: &models::{{{operationIdCamelCase}}}PathParams,
{{/pathParams.size}}
{{#queryParams.size}}
query_params: models::{{{operationIdCamelCase}}}QueryParams,
query_params: &models::{{{operationIdCamelCase}}}QueryParams,
{{/queryParams.size}}
{{^x-consumes-multipart-related}}
{{^x-consumes-multipart}}
{{#bodyParam}}
{{#vendorExtensions}}
{{^x-consumes-plain-text}}
body: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}},
body: &{{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}},
{{/x-consumes-plain-text}}
{{#x-consumes-plain-text}}
{{#isString}}
body: String,
body: &String,
{{/isString}}
{{^isString}}
body: Bytes,
body: &Bytes,
{{/isString}}
{{/x-consumes-plain-text}}
{{/vendorExtensions}}
{{/bodyParam}}
{{/x-consumes-multipart}}
{{/x-consumes-multipart-related}}
{{#x-consumes-multipart}}
body: Multipart,
body: &Multipart,
{{/x-consumes-multipart}}
{{#x-consumes-multipart-related}}
body: axum::body::Body,
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 @@ -186,38 +187,38 @@ where
{{/disableValidator}}

let result = api_impl.as_ref().{{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}(
method,
host,
cookies,
&method,
&host,
&cookies,
{{#vendorExtensions}}
{{#x-has-auth-methods}}
claims,
&claims,
{{/x-has-auth-methods}}
{{/vendorExtensions}}
{{#headerParams.size}}
header_params,
&header_params,
{{/headerParams.size}}
{{#pathParams.size}}
path_params,
&path_params,
{{/pathParams.size}}
{{#queryParams.size}}
query_params,
&query_params,
{{/queryParams.size}}
{{#vendorExtensions}}
{{^x-consumes-multipart-related}}
{{^x-consumes-multipart}}
{{#bodyParams}}
{{#-first}}
body,
&body,
{{/-first}}
{{/bodyParams}}
{{/x-consumes-multipart}}
{{/x-consumes-multipart-related}}
{{#x-consumes-multipart}}
body,
&body,
{{/x-consumes-multipart}}
{{#x-consumes-multipart-related}}
body,
&body,
{{/x-consumes-multipart-related}}
{{/vendorExtensions}}
).await;
Expand Down Expand Up @@ -342,10 +343,11 @@ 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(&method, &host, &cookies, 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
@@ -1 +1 @@
7.11.0-SNAPSHOT
7.12.0-SNAPSHOT
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ tokio = { version = "1", default-features = false, features = [
] }
tracing = { version = "0.1", features = ["attributes"] }
uuid = { version = "1", features = ["serde"] }
validator = { version = "0.19", features = ["derive"] }
validator = { version = "0.20", features = ["derive"] }

[dev-dependencies]
tracing-subscriber = "0.3"
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ server, you can easily generate a server stub.
To see how to make this your own, look here: [README]((https://openapi-generator.tech))

- API version: 1.0.0
- Generator version: 7.11.0-SNAPSHOT
- Generator version: 7.12.0-SNAPSHOT



Expand Down 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,23 @@ 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 = ()> {
#[allow(unused_variables)]
#[tracing::instrument(skip_all)]
async fn handle_error(
&self,
method: &::http::Method,
host: &axum::extract::Host,
cookies: &axum_extra::extract::CookieJar,
error: E,
) -> Result<axum::response::Response, http::StatusCode> {
tracing::error!("Unhandled error: {:?}", error);
axum::response::Response::builder()
.status(http::StatusCode::INTERNAL_SERVER_ERROR)
.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,39 +38,41 @@ 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.
///
/// GetPaymentMethodById - GET /v71/paymentMethods/{id}
async fn get_payment_method_by_id(
&self,
method: Method,
host: Host,
cookies: CookieJar,
path_params: models::GetPaymentMethodByIdPathParams,
) -> Result<GetPaymentMethodByIdResponse, ()>;
method: &Method,
host: &Host,
cookies: &CookieJar,
path_params: &models::GetPaymentMethodByIdPathParams,
) -> Result<GetPaymentMethodByIdResponse, E>;

/// Get payment methods.
///
/// GetPaymentMethods - GET /v71/paymentMethods
async fn get_payment_methods(
&self,
method: Method,
host: Host,
cookies: CookieJar,
) -> Result<GetPaymentMethodsResponse, ()>;
method: &Method,
host: &Host,
cookies: &CookieJar,
) -> Result<GetPaymentMethodsResponse, E>;

/// Make a payment.
///
/// PostMakePayment - POST /v71/payments
async fn post_make_payment(
&self,
method: Method,
host: Host,
cookies: CookieJar,
claims: Self::Claims,
body: Option<models::Payment>,
) -> Result<PostMakePaymentResponse, ()>;
method: &Method,
host: &Host,
cookies: &CookieJar,
claims: &Self::Claims,
body: &Option<models::Payment>,
) -> Result<PostMakePaymentResponse, E>;
}
Loading
Loading