From 1f8bcbd1c59ffa7114f1bbf66d19d5a695637bdf Mon Sep 17 00:00:00 2001 From: ibuibu69 Date: Fri, 11 Oct 2024 07:25:13 +0900 Subject: [PATCH] fix: Make the body of the error response into json (#402) * define AgentError and use it for network * rename enum * fix versions * change error structure * apply errors to create didcomm message * apply errors to create identifier * apply errors to create verifiable message * apply errors to find identifier * apply errors to verify didcomm message * apply errors to verify verifiable message * rename file * apply errors to send attribute * lint fix * apply errors to send custom metric * apply errors to send event * apply errors to utils * Add 2 errors * destination -> target --- agent/src/controllers/internal/network.rs | 7 +- agent/src/controllers/internal/version.rs | 11 +- agent/src/controllers/public/mod.rs | 2 +- .../public/nodex_create_didcomm_message.rs | 31 ++-- .../public/nodex_create_identifier.rs | 4 +- .../public/nodex_create_verifiable_message.rs | 13 +- .../public/nodex_find_identifier.rs | 4 +- .../public/nodex_verify_didcomm_message.rs | 54 +++++-- .../public/nodex_verify_verifiable_message.rs | 41 ++++-- .../{send_attributes.rs => send_attribute.rs} | 7 +- .../controllers/public/send_custom_metric.rs | 13 +- agent/src/controllers/public/send_event.rs | 18 ++- agent/src/controllers/public/utils.rs | 19 +-- agent/src/errors.rs | 137 ++++++++++++++++++ agent/src/main.rs | 1 + agent/src/server.rs | 2 +- 16 files changed, 295 insertions(+), 69 deletions(-) rename agent/src/controllers/public/{send_attributes.rs => send_attribute.rs} (76%) create mode 100644 agent/src/errors.rs diff --git a/agent/src/controllers/internal/network.rs b/agent/src/controllers/internal/network.rs index 89ee184a..02482ad0 100644 --- a/agent/src/controllers/internal/network.rs +++ b/agent/src/controllers/internal/network.rs @@ -1,4 +1,7 @@ -use crate::services::studio::Studio; +use crate::{ + errors::{create_agent_error, AgentErrorCode}, + services::studio::Studio, +}; use actix_web::{web, HttpRequest, HttpResponse}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -18,7 +21,7 @@ pub async fn handler( Ok(_) => Ok(HttpResponse::Ok().json("ok")), Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().json("Internal Server Error")) + Ok(create_agent_error(AgentErrorCode::NetworkInternal)) } } } diff --git a/agent/src/controllers/internal/version.rs b/agent/src/controllers/internal/version.rs index dfba7864..e0694dc2 100644 --- a/agent/src/controllers/internal/version.rs +++ b/agent/src/controllers/internal/version.rs @@ -1,4 +1,7 @@ -use crate::services::nodex::NodeX; +use crate::{ + errors::{create_agent_error, AgentErrorCode}, + services::nodex::NodeX, +}; use actix_web::{web, HttpRequest, HttpResponse}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; @@ -21,15 +24,15 @@ pub async fn handler_update( ) -> actix_web::Result { let binary_url = match json.message["binary_url"].as_str() { Some(url) => url, - None => return Ok(HttpResponse::BadRequest().json("binary_url is required")), + None => return Ok(create_agent_error(AgentErrorCode::VersionNoBinaryUrl)), }; let path = match json.message["path"].as_str() { Some(p) => p, - None => return Ok(HttpResponse::BadRequest().json("path is required")), + None => return Ok(create_agent_error(AgentErrorCode::VersionNoPath)), }; let nodex = NodeX::new(); match nodex.update_version(binary_url, PathBuf::from(path)).await { Ok(_) => Ok(HttpResponse::Ok().json("ok")), - Err(_) => Ok(HttpResponse::InternalServerError().finish()), + Err(_) => Ok(create_agent_error(AgentErrorCode::VersionInternal)), } } diff --git a/agent/src/controllers/public/mod.rs b/agent/src/controllers/public/mod.rs index b3130fc3..47b7cf8b 100644 --- a/agent/src/controllers/public/mod.rs +++ b/agent/src/controllers/public/mod.rs @@ -5,7 +5,7 @@ pub mod nodex_find_identifier; pub mod nodex_receive; pub mod nodex_verify_didcomm_message; pub mod nodex_verify_verifiable_message; -pub mod send_attributes; +pub mod send_attribute; pub mod send_custom_metric; pub mod send_event; mod utils; diff --git a/agent/src/controllers/public/nodex_create_didcomm_message.rs b/agent/src/controllers/public/nodex_create_didcomm_message.rs index 4532b408..7b1724e4 100644 --- a/agent/src/controllers/public/nodex_create_didcomm_message.rs +++ b/agent/src/controllers/public/nodex_create_didcomm_message.rs @@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize}; use protocol::didcomm::encrypted::DidCommEncryptedServiceGenerateError as S; +use crate::errors::{create_agent_error, AgentErrorCode}; use crate::nodex::utils::did_accessor::DidAccessorImpl; use crate::usecase::didcomm_message_usecase::GenerateDidcommMessageUseCaseError as U; use crate::{services::studio::Studio, usecase::didcomm_message_usecase::DidcommMessageUseCase}; @@ -35,28 +36,40 @@ pub async fn handler( Err(e) => match e { U::MessageActivity(e) => Ok(utils::handle_status(e)), U::ServiceGenerate(S::DidDocNotFound(target)) => { - log::warn!("Target DID not found. did = {}", target); - Ok(HttpResponse::NotFound().finish()) + log::warn!("target DID not found. did = {}", target); + Ok(create_agent_error( + AgentErrorCode::CreateDidCommMessageNoDid, + )) } U::ServiceGenerate(S::DidPublicKeyNotFound(e)) => { - log::warn!("cannot public key: {}", e); - Ok(HttpResponse::BadRequest().body(e.to_string())) + log::warn!("cannot find public key: {}", e); + Ok(create_agent_error( + AgentErrorCode::CreateDidCommMessageNoPubKey, + )) } U::Json(e) | U::ServiceGenerate(S::Json(e)) => { log::warn!("json error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateDidcommMessageInternal, + )) } U::ServiceGenerate(S::VcService(e)) => { - log::warn!("verify error: {}", e); - Ok(HttpResponse::Unauthorized().finish()) + log::warn!("verify failed: {}", e); + Ok(create_agent_error( + AgentErrorCode::CreateDidCommMessageVerifyFailed, + )) } U::ServiceGenerate(S::SidetreeFindRequestFailed(e)) => { log::warn!("sidetree error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateDidcommMessageInternal, + )) } U::ServiceGenerate(S::EncryptFailed(e)) => { log::warn!("decrypt failed: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateDidcommMessageInternal, + )) } }, } diff --git a/agent/src/controllers/public/nodex_create_identifier.rs b/agent/src/controllers/public/nodex_create_identifier.rs index 58ec1ad3..dca26c44 100644 --- a/agent/src/controllers/public/nodex_create_identifier.rs +++ b/agent/src/controllers/public/nodex_create_identifier.rs @@ -1,6 +1,8 @@ use actix_web::{HttpRequest, HttpResponse}; use serde::{Deserialize, Serialize}; +use crate::errors::{create_agent_error, AgentErrorCode}; + // NOTE: POST /identifiers #[derive(Deserialize, Serialize)] struct MessageContainer {} @@ -12,7 +14,7 @@ pub async fn handler(_req: HttpRequest) -> actix_web::Result { Ok(v) => Ok(HttpResponse::Ok().json(&v)), Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error(AgentErrorCode::CreateIdentifierInternal)) } } } diff --git a/agent/src/controllers/public/nodex_create_verifiable_message.rs b/agent/src/controllers/public/nodex_create_verifiable_message.rs index 687d391a..400273f4 100644 --- a/agent/src/controllers/public/nodex_create_verifiable_message.rs +++ b/agent/src/controllers/public/nodex_create_verifiable_message.rs @@ -2,6 +2,7 @@ use actix_web::{web, HttpRequest, HttpResponse}; use chrono::Utc; use serde::{Deserialize, Serialize}; +use crate::errors::{create_agent_error, AgentErrorCode}; use crate::nodex::utils::did_accessor::DidAccessorImpl; use crate::usecase::verifiable_message_usecase::CreateVerifiableMessageUseCaseError as U; use crate::{ @@ -39,15 +40,21 @@ pub async fn handler( if let Some(e) = e { log::error!("{:?}", e); } - Ok(HttpResponse::NotFound().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateVerifiableMessageNoTargetDid, + )) } U::DidVcServiceGenerate(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateVerifiableMessageInternal, + )) } U::Json(e) => { log::warn!("json error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::CreateVerifiableMessageInternal, + )) } }, } diff --git a/agent/src/controllers/public/nodex_find_identifier.rs b/agent/src/controllers/public/nodex_find_identifier.rs index ec95890a..2d64b935 100644 --- a/agent/src/controllers/public/nodex_find_identifier.rs +++ b/agent/src/controllers/public/nodex_find_identifier.rs @@ -1,6 +1,8 @@ use actix_web::{web, HttpRequest, HttpResponse}; use serde::{Deserialize, Serialize}; +use crate::errors::{create_agent_error, AgentErrorCode}; + // NOTE: GET /identifiers/${ did } #[derive(Deserialize, Serialize)] struct MessageContainer {} @@ -12,7 +14,7 @@ pub async fn handler(_req: HttpRequest, did: web::Path) -> actix_web::Re Ok(v) => Ok(HttpResponse::Ok().json(&v)), Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error(AgentErrorCode::FindIdentifierInternal)) } } } diff --git a/agent/src/controllers/public/nodex_verify_didcomm_message.rs b/agent/src/controllers/public/nodex_verify_didcomm_message.rs index cdabef1e..e1fbbcad 100644 --- a/agent/src/controllers/public/nodex_verify_didcomm_message.rs +++ b/agent/src/controllers/public/nodex_verify_didcomm_message.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use protocol::didcomm::encrypted::DidCommEncryptedServiceVerifyError as S; use protocol::didcomm::types::DidCommMessage; +use crate::errors::{create_agent_error, AgentErrorCode}; use crate::nodex::utils::did_accessor::DidAccessorImpl; use crate::{ services::studio::Studio, @@ -31,47 +32,70 @@ pub async fn handler( DidcommMessageUseCase::new(Studio::new(), utils::did_repository(), DidAccessorImpl {}); match serde_json::from_str::(&json.message) { - Err(e) => Ok(HttpResponse::BadRequest().body(e.to_string())), + Err(e) => { + log::warn!("json error: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageJsonError, + )) + } Ok(message) => match usecase.verify(message, now).await { Ok(v) => Ok(HttpResponse::Ok().json(v)), Err(e) => match e { U::MessageActivity(e) => Ok(utils::handle_status(e)), U::NotAddressedToMe => { - log::warn!("its not to me: {}", e); - Ok(HttpResponse::Forbidden().finish()) + log::warn!("this message is not addressed to me: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageNotAddressedToMe, + )) } U::ServiceVerify(S::FindSender(e)) => { log::warn!("cannot find sender: {}", e); - Ok(HttpResponse::BadRequest().body(e.to_string())) + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageNoSender, + )) } U::ServiceVerify(S::DidPublicKeyNotFound(e)) => { - log::warn!("cannot public key: {}", e); - Ok(HttpResponse::BadRequest().body(e.to_string())) + log::warn!("cannot find public key: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageNoPublicKey, + )) } U::ServiceVerify(S::MetadataBodyNotFound(e)) => { let e = e.map(|e| e.to_string()).unwrap_or("".to_string()); - log::warn!("cannot find sender: {}", e); - Ok(HttpResponse::BadRequest().body(e)) + log::warn!("cannot find metadata: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageNoMetadata, + )) } U::ServiceVerify(S::VcService(e)) => { - log::warn!("verify error: {}", e); - Ok(HttpResponse::Unauthorized().finish()) + log::warn!("verify failed: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageVerifyFailed, + )) } U::ServiceVerify(S::DidDocNotFound(target)) => { - log::warn!("Target DID not found. did = {}", target); - Ok(HttpResponse::NotFound().finish()) + log::warn!("target DID not found. DID = {}", target); + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageNoTargetDid, + )) } U::Json(e) | U::ServiceVerify(S::Json(e)) => { log::warn!("json error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageInternal, + )) } U::ServiceVerify(S::DecryptFailed(e)) => { log::warn!("decrypt failed: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageInternal, + )) } U::ServiceVerify(S::SidetreeFindRequestFailed(e)) => { log::warn!("sidetree error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::VerifyDidcommMessageInternal, + )) } }, }, diff --git a/agent/src/controllers/public/nodex_verify_verifiable_message.rs b/agent/src/controllers/public/nodex_verify_verifiable_message.rs index 842cc184..8b0788fd 100644 --- a/agent/src/controllers/public/nodex_verify_verifiable_message.rs +++ b/agent/src/controllers/public/nodex_verify_verifiable_message.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Serialize}; use protocol::verifiable_credentials::did_vc::DidVcServiceVerifyError as S; use protocol::verifiable_credentials::types::VerifiableCredentials; +use crate::errors::{create_agent_error, AgentErrorCode}; use crate::nodex::utils::did_accessor::DidAccessorImpl; use crate::usecase::verifiable_message_usecase::VerifyVerifiableMessageUseCaseError as U; use crate::{ @@ -30,31 +31,51 @@ pub async fn handler( VerifiableMessageUseCase::new(Studio::new(), repo.clone(), DidAccessorImpl {}, repo); match serde_json::from_str::(&json.message) { - Err(e) => Ok(HttpResponse::BadRequest().body(e.to_string())), + Err(e) => { + log::warn!("json error: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageJsonError, + )) + } Ok(vc) => match usecase.verify(vc, now).await { Ok(v) => Ok(HttpResponse::Ok().json(v)), Err(e) => match e { U::MessageActivity(e) => Ok(utils::handle_status(e)), U::DidVcServiceVerify(S::VerifyFailed(e)) => { - log::warn!("verify error: {}", e); - Ok(HttpResponse::Unauthorized().finish()) + log::warn!("verify failed: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageVerifyFailed, + )) } U::DidVcServiceVerify(S::FindIdentifier(e)) => { log::warn!("find identifier error: {}", e); - Ok(HttpResponse::NotFound().finish()) + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageNoIdentifier, + )) } U::DidVcServiceVerify(S::DidDocNotFound(target)) => { - log::warn!("Target DID not found. did = {}", target); - Ok(HttpResponse::NotFound().finish()) + log::warn!("target DID not found. DID = {}", target); + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageNoTargetDid, + )) + } + U::NotAddressedToMe => { + log::warn!("this message is not addressed to me: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageNotAddressedToMe, + )) } - U::NotAddressedToMe => Ok(HttpResponse::Forbidden().finish()), U::Json(e) => { log::warn!("json error: {}", e); - Ok(HttpResponse::InternalServerError().finish()) + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageInternal, + )) } U::DidVcServiceVerify(S::PublicKeyNotFound(e)) => { - log::warn!("cannot public key: {}", e); - Ok(HttpResponse::BadRequest().body(e.to_string())) + log::warn!("cannot find public key: {}", e); + Ok(create_agent_error( + AgentErrorCode::VerifyVerifiableMessageNoPublicKey, + )) } }, }, diff --git a/agent/src/controllers/public/send_attributes.rs b/agent/src/controllers/public/send_attribute.rs similarity index 76% rename from agent/src/controllers/public/send_attributes.rs rename to agent/src/controllers/public/send_attribute.rs index 171dcd59..355da0df 100644 --- a/agent/src/controllers/public/send_attributes.rs +++ b/agent/src/controllers/public/send_attribute.rs @@ -2,6 +2,7 @@ use actix_web::{web, HttpRequest, HttpResponse}; use serde::{Deserialize, Serialize}; use crate::{ + errors::{create_agent_error, AgentErrorCode}, repository::attribute_repository::AttributeStoreRequest, usecase::attribute_usecase::AttributeUsecase, }; @@ -17,10 +18,10 @@ pub async fn handler( web::Json(json): web::Json, ) -> actix_web::Result { if json.key_name.is_empty() { - return Ok(HttpResponse::BadRequest().json("key_name is required")); + return Ok(create_agent_error(AgentErrorCode::SendAttributeNoKeyName)); } if json.value.is_empty() { - return Ok(HttpResponse::BadRequest().json("value is required")); + return Ok(create_agent_error(AgentErrorCode::SendAttributeNoValue)); } let usecase = AttributeUsecase::new(); @@ -37,7 +38,7 @@ pub async fn handler( } Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().json("internal server error")) + Ok(create_agent_error(AgentErrorCode::SendAttributeInternal)) } } } diff --git a/agent/src/controllers/public/send_custom_metric.rs b/agent/src/controllers/public/send_custom_metric.rs index bddac1fc..0a6aff9d 100644 --- a/agent/src/controllers/public/send_custom_metric.rs +++ b/agent/src/controllers/public/send_custom_metric.rs @@ -3,6 +3,7 @@ use chrono::DateTime; use serde::{Deserialize, Serialize}; use crate::{ + errors::{create_agent_error, AgentErrorCode}, repository::custom_metric_repository::CustomMetricStoreRequest, usecase::custom_metric_usecase::CustomMetricUsecase, }; @@ -19,18 +20,22 @@ pub async fn handler( web::Json(json): web::Json, ) -> actix_web::Result { if json.key.is_empty() { - return Ok(HttpResponse::BadRequest().json("key is required")); + return Ok(create_agent_error(AgentErrorCode::SendCustomMetricNoKey)); } let occurred_at = match json.occurred_at.parse::() { Ok(timestamp) => match DateTime::from_timestamp(timestamp, 0) { Some(dt) => dt, _ => { - return Ok(HttpResponse::BadRequest().json("occurred_at is invalid format")); + return Ok(create_agent_error( + AgentErrorCode::SendCustomMetricInvalidOccurredAt, + )); } }, Err(_) => { - return Ok(HttpResponse::BadRequest().json("occurred_at is invalid format")); + return Ok(create_agent_error( + AgentErrorCode::SendCustomMetricInvalidOccurredAt, + )); } }; @@ -49,7 +54,7 @@ pub async fn handler( } Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().json("internal server error")) + Ok(create_agent_error(AgentErrorCode::SendCustomMetricInternal)) } } } diff --git a/agent/src/controllers/public/send_event.rs b/agent/src/controllers/public/send_event.rs index d865da34..9590665a 100644 --- a/agent/src/controllers/public/send_event.rs +++ b/agent/src/controllers/public/send_event.rs @@ -3,7 +3,9 @@ use chrono::DateTime; use serde::{Deserialize, Serialize}; use crate::{ - repository::event_repository::EventStoreRequest, usecase::event_usecase::EventUsecase, + errors::{create_agent_error, AgentErrorCode}, + repository::event_repository::EventStoreRequest, + usecase::event_usecase::EventUsecase, }; #[derive(Deserialize, Serialize)] @@ -18,21 +20,25 @@ pub async fn handler( web::Json(json): web::Json, ) -> actix_web::Result { if json.key.is_empty() { - return Ok(HttpResponse::BadRequest().json("key is required")); + return Ok(create_agent_error(AgentErrorCode::SendEventNoKey)); } if json.detail.is_empty() { - return Ok(HttpResponse::BadRequest().json("detail is required")); + return Ok(create_agent_error(AgentErrorCode::SendEventNoDetail)); } let occurred_at = match json.occurred_at.parse::() { Ok(timestamp) => match DateTime::from_timestamp(timestamp, 0) { Some(dt) => dt, _ => { - return Ok(HttpResponse::BadRequest().json("occurred_at is invalid format")); + return Ok(create_agent_error( + AgentErrorCode::SendEventInvalidOccurredAt, + )) } }, Err(_) => { - return Ok(HttpResponse::BadRequest().json("occurred_at is invalid format")); + return Ok(create_agent_error( + AgentErrorCode::SendEventInvalidOccurredAt, + )) } }; @@ -51,7 +57,7 @@ pub async fn handler( } Err(e) => { log::error!("{:?}", e); - Ok(HttpResponse::InternalServerError().json("internal server error")) + Ok(create_agent_error(AgentErrorCode::SendEventInternal)) } } } diff --git a/agent/src/controllers/public/utils.rs b/agent/src/controllers/public/utils.rs index 69e5894f..a8fa8f9f 100644 --- a/agent/src/controllers/public/utils.rs +++ b/agent/src/controllers/public/utils.rs @@ -3,6 +3,7 @@ use anyhow::Context as _; use protocol::did::did_repository::DidRepositoryImpl; +use crate::errors::{create_agent_error, AgentErrorCode}; use crate::nodex::utils::sidetree_client::SideTreeClient; use crate::repository::message_activity_repository::MessageActivityHttpError; use crate::server_config; @@ -19,24 +20,24 @@ pub fn handle_status(e: MessageActivityHttpError) -> HttpResponse { match e { MessageActivityHttpError::BadRequest(message) => { log::warn!("Bad Request: {}", message); - HttpResponse::BadRequest().body(message) - } - MessageActivityHttpError::Unauthorized(message) => { - log::warn!("Unauthorized: {}", message); - HttpResponse::Unauthorized().body(message) + create_agent_error(AgentErrorCode::MessageActivityBadRequest) } MessageActivityHttpError::Forbidden(message) => { log::warn!("Forbidden: {}", message); - HttpResponse::Forbidden().body(message) + create_agent_error(AgentErrorCode::MessageActivityForbidden) + } + MessageActivityHttpError::Unauthorized(message) => { + log::warn!("Unauthorized: {}", message); + create_agent_error(AgentErrorCode::MessageActivityUnauthorized) } MessageActivityHttpError::NotFound(message) => { log::warn!("Not Found: {}", message); - HttpResponse::NotFound().body(message) + create_agent_error(AgentErrorCode::MessageActivityNotFound) } MessageActivityHttpError::Conflict(message) => { log::warn!("Conflict: {}", message); - HttpResponse::Conflict().body(message) + create_agent_error(AgentErrorCode::MessageActivityConflict) } - _ => HttpResponse::InternalServerError().finish(), + _ => create_agent_error(AgentErrorCode::MessageActivityInternal), } } diff --git a/agent/src/errors.rs b/agent/src/errors.rs new file mode 100644 index 00000000..c055998e --- /dev/null +++ b/agent/src/errors.rs @@ -0,0 +1,137 @@ +use actix_web::HttpResponse; +use serde::Serialize; +use std::convert::From; +use thiserror::Error; + +#[derive(Serialize, Clone, Copy, Debug, Error)] +pub enum AgentErrorCode { + #[error("binary_url is required")] + VersionNoBinaryUrl = 1001, + #[error("path is required")] + VersionNoPath = 1002, + #[error("cannot find public key")] + CreateDidCommMessageNoPubKey = 1003, + #[error("sender not found")] + VerifyDidcommMessageNoSender = 1005, + #[error("public key not found")] + VerifyDidcommMessageNoPublicKey = 1004, + #[error("metadata not found")] + VerifyDidcommMessageNoMetadata = 1006, + #[error("json error")] + VerifyDidcommMessageJsonError = 1007, + #[error("public key not found")] + VerifyVerifiableMessageNoPublicKey = 1008, + #[error("json error")] + VerifyVerifiableMessageJsonError = 1009, + #[error("key_name is required")] + SendAttributeNoKeyName = 1010, + #[error("value is required")] + SendAttributeNoValue = 1011, + #[error("key is required")] + SendCustomMetricNoKey = 1012, + #[error("occurred_at is invalid format")] + SendCustomMetricInvalidOccurredAt = 1013, + #[error("key is invalid")] + SendEventNoKey = 1014, + #[error("detail is invalid")] + SendEventNoDetail = 1015, + #[error("occurred_at is invalid format")] + SendEventInvalidOccurredAt = 1016, + #[error("Bad Request")] + MessageActivityBadRequest = 1017, + + #[error("this message is not addressed to me")] + VerifyDidcommMessageNotAddressedToMe = 2001, + #[error("this message is not addressed to me")] + VerifyVerifiableMessageNotAddressedToMe = 2002, + #[error("Forbidden")] + MessageActivityForbidden = 2003, + + #[error("verify failed")] + CreateDidCommMessageVerifyFailed = 3001, + #[error("verify failed")] + VerifyDidcommMessageVerifyFailed = 3002, + #[error("verify failed")] + VerifyVerifiableMessageVerifyFailed = 3003, + #[error("Unauthorized")] + MessageActivityUnauthorized = 3004, + + #[error("target DID not found")] + CreateDidCommMessageNoDid = 4001, + #[error("target DID not found")] + CreateVerifiableMessageNoTargetDid = 4002, + #[error("target DID not found")] + VerifyDidcommMessageNoTargetDid = 4003, + #[error("identifier not found")] + VerifyVerifiableMessageNoIdentifier = 4004, + #[error("target DID not found")] + VerifyVerifiableMessageNoTargetDid = 4005, + #[error("Not Found")] + MessageActivityNotFound = 4006, + + #[error("Internal Server Error")] + NetworkInternal = 5001, + #[error("Internal Server Error")] + VersionInternal = 5002, + #[error("Internal Server Error")] + CreateDidcommMessageInternal = 5003, + #[error("Internal Server Error")] + CreateIdentifierInternal = 5004, + #[error("Internal Server Error")] + CreateVerifiableMessageInternal = 5005, + #[error("Internal Server Error")] + FindIdentifierInternal = 5006, + #[error("Internal Server Error")] + VerifyDidcommMessageInternal = 5007, + #[error("Internal Server Error")] + VerifyVerifiableMessageInternal = 5008, + #[error("Internal Server Error")] + SendAttributeInternal = 5009, + #[error("Internal Server Error")] + SendCustomMetricInternal = 5010, + #[error("Internal Server Error")] + SendEventInternal = 5011, + #[error("Internal Server Error")] + MessageActivityInternal = 5012, + + #[error("Conflict")] + MessageActivityConflict = 6001, +} + +#[derive(Serialize)] +pub struct AgentError { + code: AgentErrorCode, + message: String, +} + +impl AgentError { + pub fn new(code: AgentErrorCode) -> Self { + Self { + code, + message: format!("{}", code), + } + } +} +impl From for HttpResponse { + fn from(error: AgentError) -> Self { + let code = error.code as u16; + if (1000..2000).contains(&code) { + HttpResponse::BadRequest().json(error) + } else if (2000..3000).contains(&code) { + HttpResponse::Forbidden().json(error) + } else if (3000..4000).contains(&code) { + HttpResponse::Unauthorized().json(error) + } else if (4000..5000).contains(&code) { + HttpResponse::NotFound().json(error) + } else if (5000..6000).contains(&code) { + HttpResponse::InternalServerError().json(error) + } else if (6000..6100).contains(&code) { + HttpResponse::Conflict().json(error) + } else { + HttpResponse::InternalServerError().json(error) + } + } +} +pub fn create_agent_error(code: AgentErrorCode) -> HttpResponse { + AgentError::new(code).into() +} diff --git a/agent/src/main.rs b/agent/src/main.rs index d22920ef..24611bf6 100644 --- a/agent/src/main.rs +++ b/agent/src/main.rs @@ -39,6 +39,7 @@ use usecase::metric_usecase::MetricUsecase; mod config; mod controllers; +mod errors; mod handlers; mod network; mod nodex; diff --git a/agent/src/server.rs b/agent/src/server.rs index 84a1d3a5..d0a5ffe7 100644 --- a/agent/src/server.rs +++ b/agent/src/server.rs @@ -84,7 +84,7 @@ fn config_app( ) .route( "/attributes", - web::post().to(controllers::public::send_attributes::handler), + web::post().to(controllers::public::send_attribute::handler), ) // NOTE: Internal (Private) Routes .service(