Fine-tune passing errors from the server to the client
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
use anyhow::{anyhow, Error};
|
||||
use anyhow::Result;
|
||||
use lldap_model::*;
|
||||
|
||||
use yew::callback::Callback;
|
||||
@@ -9,21 +9,32 @@ use yew::services::fetch::{FetchService, FetchTask, Request, Response};
|
||||
pub struct HostService {}
|
||||
|
||||
impl HostService {
|
||||
pub fn list_users(&mut self, request: ListUsersRequest, callback: Callback<Result<Vec<User>, Error>>) -> Result<FetchTask, Error> {
|
||||
pub fn list_users(
|
||||
&mut self,
|
||||
request: ListUsersRequest,
|
||||
callback: Callback<Result<Vec<User>>>,
|
||||
) -> Result<FetchTask> {
|
||||
let url = format!("/api/users");
|
||||
let handler = move |response: Response<Json<Result<Vec<User>, Error>>>| {
|
||||
let (meta, Json(data)) = response.into_parts();
|
||||
if meta.status.is_success() {
|
||||
callback.emit(data)
|
||||
} else {
|
||||
callback.emit(Err(anyhow!(
|
||||
"{}: error getting users from /api/users",
|
||||
meta.status
|
||||
)))
|
||||
}
|
||||
};
|
||||
let request = Request::post(url.as_str()).header("Content-Type", "application/json").body(Json(&request)).unwrap();
|
||||
let handler =
|
||||
move |response: Response<Result<String>>| {
|
||||
let (meta, maybe_data) = response.into_parts();
|
||||
match maybe_data {
|
||||
Ok(data) => {
|
||||
if meta.status.is_success() {
|
||||
callback.emit(serde_json::from_str(&data).map_err(|e| {
|
||||
anyhow::format_err!("Could not parse response: {}", e)
|
||||
}))
|
||||
} else {
|
||||
callback.emit(Err(anyhow::anyhow!("[{}]: {}", meta.status, data)))
|
||||
}
|
||||
}
|
||||
Err(e) => callback.emit(Err(anyhow::anyhow!("Could not fetch: {}", e))),
|
||||
}
|
||||
};
|
||||
let request = Request::post(url.as_str())
|
||||
.header("Content-Type", "application/json")
|
||||
.body(Json(&request))
|
||||
.unwrap();
|
||||
FetchService::fetch(request, handler.into())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,9 +41,7 @@ impl Component for App {
|
||||
Ok(task) => self.task = Some(task),
|
||||
Err(e) => {
|
||||
self.task = None;
|
||||
ConsoleService::log(
|
||||
format!("Error trying to fetch users: {:?}", e).as_str(),
|
||||
)
|
||||
ConsoleService::log(format!("Error trying to fetch users: {}", e).as_str())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,7 +51,7 @@ impl Component for App {
|
||||
}
|
||||
Msg::ListUsersResponse(Err(e)) => {
|
||||
self.task = None;
|
||||
ConsoleService::log(format!("Error listing users: {:?}", e).as_str())
|
||||
ConsoleService::log(format!("Error listing users: {}", e).as_str())
|
||||
}
|
||||
}
|
||||
true
|
||||
|
||||
Reference in New Issue
Block a user