add internal_err! macro to replace some unwrap()

This commit is contained in:
Peter Cai 2020-04-07 18:53:45 +08:00
parent a2fa677514
commit 5467fa6e6d
No known key found for this signature in database
GPG key ID: 71F5FB4E4F3FD54F
3 changed files with 30 additions and 16 deletions

View file

@ -43,10 +43,12 @@ async fn default_route(_req: Request, _url: Url) -> MyResult<Response> {
} }
async fn hello_world(_req: Request, _url: Url) -> MyResult<Response> { async fn hello_world(_req: Request, _url: Url) -> MyResult<Response> {
Ok(Response::new_with_opt_str_and_init( internal_err!(
Some("Hello, world from Rust"), Response::new_with_opt_str_and_init(
ResponseInit::new().status(200) Some("Hello, world from Rust"),
).unwrap()) ResponseInit::new().status(200)
)
)
} }
#[wasm_bindgen] #[wasm_bindgen]

View file

@ -47,18 +47,21 @@ async fn get_actions(_req: Request, url: Url) -> MyResult<Response> {
actions actions
}; };
Ok(Response::new_with_opt_str_and_init( internal_err!(
Some(&serde_json::to_string(&info) Response::new_with_opt_str_and_init(
.map_err(|_| Error::InternalError())?), Some(&internal_err!(
ResponseInit::new() serde_json::to_string(&info)
.status(200) )?),
.headers({ ResponseInit::new()
let headers = Headers::new().unwrap(); .status(200)
headers.set("Content-Type", "application/json").unwrap(); .headers({
cors!(headers); let headers = Headers::new().unwrap();
headers headers.set("Content-Type", "application/json").unwrap();
}.as_ref()) cors!(headers);
).unwrap()) headers
}.as_ref())
)
)
} }
pub enum Verb { pub enum Verb {

View file

@ -25,6 +25,15 @@ macro_rules! cors {
}; };
} }
// Ignore any error and return InternalError for them all
// Used in place of ugly `.unwrap()`.
#[macro_export]
macro_rules! internal_err {
($result:expr) => {
$result.map_err(|_| crate::utils::Error::InternalError())
}
}
pub type MyResult<T> = Result<T, Error>; pub type MyResult<T> = Result<T, Error>;
pub enum Error { pub enum Error {