Skip to content

Commit

Permalink
editoast: forward core error type
Browse files Browse the repository at this point in the history
  • Loading branch information
Khoyo committed Oct 16, 2023
1 parent 7c02b7b commit c6f5384
Showing 1 changed file with 40 additions and 3 deletions.
43 changes: 40 additions & 3 deletions editoast/src/core/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ pub mod simulation;
pub mod stdcm;
pub mod version;

use std::marker::PhantomData;
use std::{marker::PhantomData, collections::HashMap, fmt::Display};

use crate::error::{InternalError, Result};
use actix_http::StatusCode;
use async_trait::async_trait;
use colored::{ColoredString, Colorize};
use editoast_derive::EditoastError;
Expand All @@ -20,6 +21,7 @@ use log::info;
use reqwest::Url;
use serde::{de::DeserializeOwned, Serialize};
use serde_derive::Deserialize;
use serde_json::Value;
use thiserror::Error;

const MAX_RETRIES: u8 = 5;
Expand Down Expand Up @@ -108,8 +110,9 @@ impl CoreClient {

log::error!(target: "editoast::coreclient", "{method_s} {path} {status}", status = status.to_string().bold().red());

// We try to deserialize the response as an InternalError in order to retain the context of the core error
if let Ok(mut internal_error) = <Json<InternalError>>::from_bytes(bytes.as_ref()) {
// We try to deserialize the response as an StandardCoreError in order to retain the context of the core error
if let Ok(core_error) = <Json<StandardCoreError>>::from_bytes(bytes.as_ref()) {
let mut internal_error: InternalError = core_error.into();
internal_error.set_status(status);
return Err(internal_error);
}
Expand Down Expand Up @@ -316,6 +319,40 @@ enum CoreError {
NoResponseContent,
}

#[derive(Debug, Deserialize)]
pub struct StandardCoreError {
#[serde(skip)]
status: StatusCode,
#[serde(rename = "type")]
error_type: Value,
context: HashMap<String, Value>,
message: String,
}

impl crate::error::EditoastError for StandardCoreError {
fn get_type(&self) -> &'static str {
"forwarded_core_error"
}

fn get_status(&self) -> StatusCode {
self.status
}

fn context(&self) -> HashMap<String, Value> {
let mut context_with_type = self.context.clone();
context_with_type.insert("type".to_owned(), self.error_type.clone());
context_with_type
}
}

impl std::error::Error for StandardCoreError {}

impl Display for StandardCoreError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}

impl From<reqwest::Error> for CoreError {
fn from(value: reqwest::Error) -> Self {
// Since we should retry the request it's useful to have its own kind of error.
Expand Down

0 comments on commit c6f5384

Please sign in to comment.