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> {
Ok(Response::new_with_opt_str_and_init(
Some("Hello, world from Rust"),
ResponseInit::new().status(200)
).unwrap())
internal_err!(
Response::new_with_opt_str_and_init(
Some("Hello, world from Rust"),
ResponseInit::new().status(200)
)
)
}
#[wasm_bindgen]

View File

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