Skip to content

Commit

Permalink
Add bad request responses
Browse files Browse the repository at this point in the history
  • Loading branch information
paulhauner committed Sep 5, 2020
1 parent 044da99 commit 5a6e1a1
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
6 changes: 3 additions & 3 deletions beacon_node/http_api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ pub fn serve<T: BeaconChainTypes>(
let relative_epoch =
RelativeEpoch::from_epoch(state.current_epoch(), epoch).map_err(
|_| {
crate::reject::custom_not_found(format!(
crate::reject::custom_bad_request(format!(
"only previous, current and next epochs are supported"
))
},
Expand Down Expand Up @@ -227,7 +227,7 @@ pub fn serve<T: BeaconChainTypes>(
// It is not acceptable to query with a slot that is not within the
// specified epoch.
if slot.epoch(T::EthSpec::slots_per_epoch()) != epoch {
return Err(crate::reject::custom_not_found(format!(
return Err(crate::reject::custom_bad_request(format!(
"{} is not in epoch {}",
slot, epoch
)));
Expand All @@ -237,7 +237,7 @@ pub fn serve<T: BeaconChainTypes>(
let committee = committee_cache
.get_beacon_committee(slot, index)
.ok_or_else(|| {
crate::reject::custom_not_found(format!(
crate::reject::custom_bad_request(format!(
"committee index {} does not exist in epoch {}",
index, epoch
))
Expand Down
12 changes: 12 additions & 0 deletions beacon_node/http_api/src/reject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,15 @@ pub fn custom_not_found(msg: String) -> warp::reject::Rejection {
warp::reject::custom(CustomNotFound(msg))
}

#[derive(Debug)]
pub struct CustomBadRequest(pub String);

impl Reject for CustomBadRequest {}

pub fn custom_bad_request(msg: String) -> warp::reject::Rejection {
warp::reject::custom(CustomBadRequest(msg))
}

/// An API error serializable to JSON.
#[derive(Serialize)]
struct ErrorMessage {
Expand Down Expand Up @@ -61,6 +70,9 @@ pub async fn handle_rejection(err: warp::Rejection) -> Result<impl warp::Reply,
} else if let Some(e) = err.find::<crate::reject::CustomNotFound>() {
code = StatusCode::NOT_FOUND;
message = format!("NOT_FOUND: {}", e.0);
} else if let Some(e) = err.find::<crate::reject::CustomBadRequest>() {
code = StatusCode::BAD_REQUEST;
message = format!("BAD_REQUEST: {}", e.0);
} else {
// We should have expected this... Just log and say its a 500
eprintln!("unhandled rejection: {:?}", err);
Expand Down

0 comments on commit 5a6e1a1

Please sign in to comment.