Skip to content
This repository has been archived by the owner on Jun 18, 2024. It is now read-only.

Commit

Permalink
Handle error for Post request
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianEffe committed Aug 15, 2023
1 parent 84db442 commit bf2df57
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 10 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ tracing-subscriber = "0.3.17"
tower-http = { version = "0.4.3", features = ["trace"] }
md5 = "0.7.0"
base62 = "2.0.2"
anyhow = "1.0.73"

[dependencies.sqlx]
version = "0.7.1"
Expand Down
16 changes: 16 additions & 0 deletions src/app_error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};

pub struct AppError(pub anyhow::Error);

impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod app_error;
pub mod configuration;
pub mod key_generator;
pub mod model;
Expand Down
17 changes: 7 additions & 10 deletions src/routes/full_url.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use crate::{
key_generator::generate, model::UrlRequestModel, schema::CreateShortUrlSchema, AppState,
app_error::AppError, key_generator::generate, model::UrlRequestModel,
schema::CreateShortUrlSchema, AppState,
};
use anyhow::anyhow;
use axum::{extract::State, Json};
use chrono::Utc;
use sqlx::Error;
Expand All @@ -10,30 +12,25 @@ use uuid::Uuid;
pub async fn full_url(
State(data): State<Arc<AppState>>,
Json(payload): Json<CreateShortUrlSchema>,
) -> String {
) -> Result<String, AppError> {
let mut retry_count = 3;

while retry_count > 0 {
let query_result = insert_in_db(&payload.url, State(data.clone())).await;

match query_result {
Ok(request) => {
println!("okay received testing: {:?}", request);
return request.extension;
return Ok(request.extension);
}
Err(e) => {
println!("failed with error: {:?}", e);
//TODO : - For now assume is failing because of error code 23505, that stands for
//duplicate key
if retry_count == 1 {
return "error".to_string();
return Err(AppError(e.into()));
}
retry_count -= 1;
}
}
}

"internal server error".to_string()
Err(AppError(anyhow!("Something went wrong")))
}

async fn insert_in_db(
Expand Down

0 comments on commit bf2df57

Please sign in to comment.