Returning a 400 status code will have us constructing the ApiGatewayProxyResponse type, which allows us to set the status code on the status_code field. The value we pass in must be a number, specifically an i64, although not all numbers have associated http status codes.
We'll bring serde_json::json into scope in main.rs so that we can construct a JSON response alongside our 400 status code.
use serde_json::json;
Inside of the Some("") match which means we're searching for an empty pokemon, we'll write our 400 response, while inside of None, we'll panic because that should never happen.
match requested_pokemon {
Some("") => {
let error_message = serde_json::to_string(&json!({
"error": "searched for empty pokemon"
}))?;
let response = ApiGatewayProxyResponse {
status_code: 400,
headers: HeaderMap::new(),
multi_value_headers: HeaderMap::new(),
body: Some(Body::Text(error_message)),
is_base64_encoded: Some(false),
};
Ok(response)
},
None => panic!("requested_pokemon is None, which should never happen"),
We also have to update our test to expect the response we've constructed and not check for a panic.
#[tokio::test]
async fn handler_handles_empty_pokemon() {
let event = fake_request("/api/pokemon//".to_string());
assert_eq!(
handler(event.clone(), Context::default())
.await
.unwrap(),
ApiGatewayProxyResponse {
status_code: 400,
headers: HeaderMap::new(),
multi_value_headers: HeaderMap::new(),
body: Some(Body::Text(
serde_json::to_string(&json!({
"error": "searched for empty pokemon"
})).unwrap()
)),
is_base64_encoded: Some(false),
}
);
}
All tests should now pass again