Fine-tune passing errors from the server to the client

This commit is contained in:
Valentin Tolmer 2021-05-10 10:21:24 +02:00
parent 6b8cccede0
commit e1047124fa
5 changed files with 49 additions and 34 deletions

View File

@ -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())
}
}

View File

@ -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

View File

@ -1,4 +1,4 @@
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Eq, Debug, Serialize, Deserialize, Clone)]
pub struct BindRequest {

View File

@ -100,16 +100,10 @@ fn map_field(field: &str) -> Result<String> {
fn convert_filter(filter: &LdapFilter) -> Result<RequestFilter> {
match filter {
LdapFilter::And(filters) => Ok(RequestFilter::And(
filters
.iter()
.map(convert_filter)
.collect::<Result<_>>()?,
filters.iter().map(convert_filter).collect::<Result<_>>()?,
)),
LdapFilter::Or(filters) => Ok(RequestFilter::Or(
filters
.iter()
.map(convert_filter)
.collect::<Result<_>>()?,
filters.iter().map(convert_filter).collect::<Result<_>>()?,
)),
LdapFilter::Not(filter) => Ok(RequestFilter::Not(Box::new(convert_filter(&*filter)?))),
LdapFilter::Equality(field, value) => {

View File

@ -1,4 +1,4 @@
use crate::domain::handler::*;
use crate::domain::{error::Error, handler::*};
use crate::infra::configuration::Configuration;
use actix_files::{Files, NamedFile};
use actix_http::HttpServiceBuilder;
@ -16,6 +16,16 @@ async fn index(req: HttpRequest) -> actix_web::Result<NamedFile> {
Ok(NamedFile::open(path)?)
}
fn error_to_http_response<T>(error: Error) -> ApiResult<T> {
ApiResult::Right(
match error {
Error::AuthenticationError(_) => HttpResponse::Unauthorized(),
Error::DatabaseError(_) => HttpResponse::InternalServerError(),
}
.body(error.to_string()),
)
}
type ApiResult<M> = actix_web::Either<web::Json<M>, HttpResponse>;
async fn user_list_handler<Backend>(
@ -26,10 +36,11 @@ where
Backend: BackendHandler + 'static,
{
let req: ListUsersRequest = info.clone();
match data.backend_handler.list_users(req).await {
Ok(res) => ApiResult::Left(web::Json(res)),
Err(_) => ApiResult::Right(HttpResponse::InternalServerError().finish()),
}
data.backend_handler
.list_users(req)
.await
.map(|res| ApiResult::Left(web::Json(res)))
.unwrap_or_else(error_to_http_response)
}
fn api_config<Backend>(cfg: &mut web::ServiceConfig)
@ -41,9 +52,10 @@ where
.error_handler(|err, _req| {
// create custom error response
log::error!("API error: {}", err);
let msg = err.to_string();
actix_web::error::InternalError::from_response(
err,
HttpResponse::Conflict().finish().into(),
HttpResponse::BadRequest().body(msg).into(),
)
.into()
});