make internal_err an extension trait

This commit is contained in:
Peter Cai 2020-04-07 19:40:22 +08:00
parent 5467fa6e6d
commit 0547cdd0c3
No known key found for this signature in database
GPG Key ID: 71F5FB4E4F3FD54F
3 changed files with 26 additions and 29 deletions

View File

@ -7,7 +7,7 @@ mod router;
mod sn; mod sn;
use cfg_if::cfg_if; use cfg_if::cfg_if;
use utils::{Error, MyResult}; use utils::*;
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use web_sys::*; use web_sys::*;
@ -43,12 +43,10 @@ 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> {
internal_err!( Response::new_with_opt_str_and_init(
Response::new_with_opt_str_and_init( Some("Hello, world from Rust"),
Some("Hello, world from Rust"), ResponseInit::new().status(200)
ResponseInit::new().status(200) ).internal_err()
)
)
} }
#[wasm_bindgen] #[wasm_bindgen]

View File

@ -1,7 +1,7 @@
// Interface for Standard Notes (Actions) // Interface for Standard Notes (Actions)
use crate::CONFIG; use crate::CONFIG;
use crate::router::Router; use crate::router::Router;
use crate::utils::{Error, MyResult}; use crate::utils::*;
use serde::{Serialize, Serializer}; use serde::{Serialize, Serializer};
use std::vec::Vec; use std::vec::Vec;
use web_sys::*; use web_sys::*;
@ -47,21 +47,17 @@ async fn get_actions(_req: Request, url: Url) -> MyResult<Response> {
actions actions
}; };
internal_err!( Response::new_with_opt_str_and_init(
Response::new_with_opt_str_and_init( Some(&serde_json::to_string(&info).internal_err()?),
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); ).internal_err()
headers
}.as_ref())
)
)
} }
pub enum Verb { pub enum Verb {

View File

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