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 lldap_model::*;
use yew::callback::Callback; use yew::callback::Callback;
@ -9,21 +9,32 @@ use yew::services::fetch::{FetchService, FetchTask, Request, Response};
pub struct HostService {} pub struct HostService {}
impl 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 url = format!("/api/users");
let handler = move |response: Response<Json<Result<Vec<User>, Error>>>| { let handler =
let (meta, Json(data)) = response.into_parts(); move |response: Response<Result<String>>| {
let (meta, maybe_data) = response.into_parts();
match maybe_data {
Ok(data) => {
if meta.status.is_success() { if meta.status.is_success() {
callback.emit(data) callback.emit(serde_json::from_str(&data).map_err(|e| {
anyhow::format_err!("Could not parse response: {}", e)
}))
} else { } else {
callback.emit(Err(anyhow!( callback.emit(Err(anyhow::anyhow!("[{}]: {}", meta.status, data)))
"{}: error getting users from /api/users", }
meta.status }
))) 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(); let request = Request::post(url.as_str())
.header("Content-Type", "application/json")
.body(Json(&request))
.unwrap();
FetchService::fetch(request, handler.into()) FetchService::fetch(request, handler.into())
} }
} }

View File

@ -41,9 +41,7 @@ impl Component for App {
Ok(task) => self.task = Some(task), Ok(task) => self.task = Some(task),
Err(e) => { Err(e) => {
self.task = None; self.task = None;
ConsoleService::log( ConsoleService::log(format!("Error trying to fetch users: {}", e).as_str())
format!("Error trying to fetch users: {:?}", e).as_str(),
)
} }
} }
} }
@ -53,7 +51,7 @@ impl Component for App {
} }
Msg::ListUsersResponse(Err(e)) => { Msg::ListUsersResponse(Err(e)) => {
self.task = None; self.task = None;
ConsoleService::log(format!("Error listing users: {:?}", e).as_str()) ConsoleService::log(format!("Error listing users: {}", e).as_str())
} }
} }
true true

View File

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

View File

@ -100,16 +100,10 @@ fn map_field(field: &str) -> Result<String> {
fn convert_filter(filter: &LdapFilter) -> Result<RequestFilter> { fn convert_filter(filter: &LdapFilter) -> Result<RequestFilter> {
match filter { match filter {
LdapFilter::And(filters) => Ok(RequestFilter::And( LdapFilter::And(filters) => Ok(RequestFilter::And(
filters filters.iter().map(convert_filter).collect::<Result<_>>()?,
.iter()
.map(convert_filter)
.collect::<Result<_>>()?,
)), )),
LdapFilter::Or(filters) => Ok(RequestFilter::Or( LdapFilter::Or(filters) => Ok(RequestFilter::Or(
filters filters.iter().map(convert_filter).collect::<Result<_>>()?,
.iter()
.map(convert_filter)
.collect::<Result<_>>()?,
)), )),
LdapFilter::Not(filter) => Ok(RequestFilter::Not(Box::new(convert_filter(&*filter)?))), LdapFilter::Not(filter) => Ok(RequestFilter::Not(Box::new(convert_filter(&*filter)?))),
LdapFilter::Equality(field, value) => { 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 crate::infra::configuration::Configuration;
use actix_files::{Files, NamedFile}; use actix_files::{Files, NamedFile};
use actix_http::HttpServiceBuilder; use actix_http::HttpServiceBuilder;
@ -16,6 +16,16 @@ async fn index(req: HttpRequest) -> actix_web::Result<NamedFile> {
Ok(NamedFile::open(path)?) 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>; type ApiResult<M> = actix_web::Either<web::Json<M>, HttpResponse>;
async fn user_list_handler<Backend>( async fn user_list_handler<Backend>(
@ -26,10 +36,11 @@ where
Backend: BackendHandler + 'static, Backend: BackendHandler + 'static,
{ {
let req: ListUsersRequest = info.clone(); let req: ListUsersRequest = info.clone();
match data.backend_handler.list_users(req).await { data.backend_handler
Ok(res) => ApiResult::Left(web::Json(res)), .list_users(req)
Err(_) => ApiResult::Right(HttpResponse::InternalServerError().finish()), .await
} .map(|res| ApiResult::Left(web::Json(res)))
.unwrap_or_else(error_to_http_response)
} }
fn api_config<Backend>(cfg: &mut web::ServiceConfig) fn api_config<Backend>(cfg: &mut web::ServiceConfig)
@ -41,9 +52,10 @@ where
.error_handler(|err, _req| { .error_handler(|err, _req| {
// create custom error response // create custom error response
log::error!("API error: {}", err); log::error!("API error: {}", err);
let msg = err.to_string();
actix_web::error::InternalError::from_response( actix_web::error::InternalError::from_response(
err, err,
HttpResponse::Conflict().finish().into(), HttpResponse::BadRequest().body(msg).into(),
) )
.into() .into()
}); });