Skip to content

Commit

Permalink
[api] return 400 bad request error for method not allowed request
Browse files Browse the repository at this point in the history
  • Loading branch information
Xiao Li authored and bors-libra committed Oct 27, 2021
1 parent fdb51ed commit 85be953
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 7 additions & 1 deletion api/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::{accounts, context::Context, events, log, transactions};
use diem_api_types::{Error, Response};

use std::convert::Infallible;
use warp::{http::StatusCode, reply, Filter, Rejection, Reply};
use warp::{http::StatusCode, reject::MethodNotAllowed, reply, Filter, Rejection, Reply};

pub fn routes(context: Context) -> impl Filter<Extract = impl Reply, Error = Infallible> + Clone {
index(context.clone())
Expand Down Expand Up @@ -38,6 +38,12 @@ async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
} else if let Some(error) = err.find::<Error>() {
code = error.status_code();
body = reply::json(error);
} else if err.find::<MethodNotAllowed>().is_some() {
code = StatusCode::BAD_REQUEST;
body = reply::json(&Error::new(
code,
"Method not allowed or request body is invalid.".to_owned(),
));
} else {
code = StatusCode::INTERNAL_SERVER_ERROR;
body = reply::json(&Error::new(code, format!("unexpected error: {:?}", err)));
Expand Down
16 changes: 16 additions & 0 deletions api/src/tests/index_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,19 @@ async fn test_returns_not_found_for_the_invalid_path() {
let resp = context.expect_status_code(404).get("/invalid_path").await;
assert_eq!(json!({"code": 404, "message": "Not Found"}), resp)
}

#[tokio::test]
async fn test_return_bad_request_if_method_not_allowed() {
let context = new_test_context();
let resp = context
.expect_status_code(400)
.post("/accounts/0x1/resources", json!({}))
.await;

let expected = json!({
"code": 400,
"message": "Method not allowed or request body is invalid.",
});

assert_eq!(expected, resp);
}

0 comments on commit 85be953

Please sign in to comment.