Skip to content

Commit

Permalink
Add the error macros bail and warn
Browse files Browse the repository at this point in the history
  • Loading branch information
photino committed Nov 14, 2023
1 parent 02c76d1 commit 3bf82de
Show file tree
Hide file tree
Showing 40 changed files with 314 additions and 244 deletions.
2 changes: 1 addition & 1 deletion examples/actix-app/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ pub async fn refresh(req: Request) -> Result {
pub async fn logout(req: Request) -> Result {
let user_session = req
.get_data::<UserSession<_>>()
.ok_or_else(|| Error::new("401 Unauthorized: the user session is invalid"))
.ok_or_else(|| warn!("401 Unauthorized: the user session is invalid"))
.extract(&req)?;

let mut mutations = Map::from_entry("status", "SignedOut");
Expand Down
2 changes: 1 addition & 1 deletion examples/axum-app/src/controller/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub async fn refresh(req: Request) -> Result {
pub async fn logout(req: Request) -> Result {
let user_session = req
.get_data::<UserSession<_>>()
.ok_or_else(|| Error::new("401 Unauthorized: the user session is invalid"))
.ok_or_else(|| warn!("401 Unauthorized: the user session is invalid"))
.extract(&req)?;

let mut mutations = Map::from_entry("status", "SignedOut");
Expand Down
2 changes: 2 additions & 0 deletions zino-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ http = "0.2.10"
http-body = "0.4.5"
intl-memoizer = "0.5.1"
jwt-simple = "0.11.9"
md-5 = "0.10.6"
metrics = "0.21.1"
metrics-exporter-prometheus = "0.12.1"
mime = "0.3.17"
Expand Down Expand Up @@ -314,6 +315,7 @@ base64-simd = "0.8.0"
criterion = "0.5.1"
data-encoding = "2.4.0"
libsm = "0.5.1"
sm3 = "0.4.2"
sonic-rs = "0.2.4"
tinyvec = { version = "1.6.0", features = ["alloc"] }
uuid-simd = "0.8.0"
Expand Down
6 changes: 3 additions & 3 deletions zino-core/src/application/http_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
error::Error,
extension::{HeaderMapExt, JsonObjectExt, TomlTableExt},
trace::TraceContext,
JsonValue, Map, Uuid,
warn, JsonValue, Map, Uuid,
};
use reqwest::{
header::{self, HeaderMap, HeaderName},
Expand Down Expand Up @@ -106,7 +106,7 @@ pub(crate) fn request_builder(
if options.is_none() || options.is_some_and(|map| map.is_empty()) {
let request_builder = SHARED_HTTP_CLIENT_WITH_MIDDLEWARE
.get()
.ok_or_else(|| Error::new("fail to get the global http client"))?
.ok_or_else(|| warn!("fail to get the global http client"))?
.request(Method::GET, resource);
return Ok(request_builder);
}
Expand All @@ -118,7 +118,7 @@ pub(crate) fn request_builder(
.unwrap_or(Method::GET);
let mut request_builder = SHARED_HTTP_CLIENT_WITH_MIDDLEWARE
.get()
.ok_or_else(|| Error::new("fail to get the global http client"))?
.ok_or_else(|| warn!("fail to get the global http client"))?
.request(method, resource);
let mut headers = HeaderMap::new();
if let Some(query) = options.get("query") {
Expand Down
6 changes: 3 additions & 3 deletions zino-core/src/auth/client_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
datetime::DateTime,
error::Error,
extension::{JsonObjectExt, TomlTableExt},
Map, SharedString,
warn, Map, SharedString,
};
use parking_lot::RwLock;
use std::{marker::PhantomData, time::Duration};
Expand Down Expand Up @@ -44,11 +44,11 @@ impl<S: ?Sized> ClientCredentials<S> {
pub fn try_from_config(config: &'static Table) -> Result<Self, Error> {
let client_id = config
.get_str("client-id")
.ok_or_else(|| Error::new("the `client-id` field should be specified"))?;
.ok_or_else(|| warn!("the `client-id` field should be specified"))?;
let client_key = config.get_str("client-key").unwrap_or_default();
let client_secret = config
.get_str("client-secret")
.ok_or_else(|| Error::new("the `client-secret` field should be specified"))?;
.ok_or_else(|| warn!("the `client-secret` field should be specified"))?;
Ok(Self {
client_id: client_id.into(),
client_key: client_key.into(),
Expand Down
6 changes: 3 additions & 3 deletions zino-core/src/auth/oauth2_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{error::Error, extension::TomlTableExt};
use crate::{error::Error, extension::TomlTableExt, warn};
use oauth2::{
basic::BasicClient, AuthType::RequestBody, AuthUrl, ClientId, ClientSecret,
DeviceAuthorizationUrl, IntrospectionUrl, RedirectUrl, RevocationUrl, TokenUrl,
Expand Down Expand Up @@ -31,13 +31,13 @@ impl OAuth2Client {
let client_id = config
.get_str("client-id")
.map(|s| ClientId::new(s.to_owned()))
.ok_or_else(|| Error::new("the `client-id` field should be specified"))?;
.ok_or_else(|| warn!("the `client-id` field should be specified"))?;
let client_secret = config
.get_str("client-secret")
.map(|s| ClientSecret::new(s.to_owned()));
let auth_url = config
.get_str("auth-url")
.ok_or_else(|| Error::new("the `auth-url` field should be specified"))?
.ok_or_else(|| warn!("the `auth-url` field should be specified"))?
.parse()
.map(AuthUrl::from_url)?;
let token_url = config
Expand Down
8 changes: 4 additions & 4 deletions zino-core/src/auth/oidc_client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{error::Error, extension::TomlTableExt};
use crate::{error::Error, extension::TomlTableExt, warn};
use openidconnect::{
core::{CoreClient, CoreJsonWebKey, CoreProviderMetadata},
reqwest::http_client,
Expand Down Expand Up @@ -63,21 +63,21 @@ impl OidcClient {
let client_id = config
.get_str("client-id")
.map(|s| ClientId::new(s.to_owned()))
.ok_or_else(|| Error::new("the `client-id` field should be specified"))?;
.ok_or_else(|| warn!("the `client-id` field should be specified"))?;
let client_secret = config
.get_str("client-secret")
.map(|s| ClientSecret::new(s.to_owned()));
let issuer_url = config
.get_str("issuer-url")
.ok_or_else(|| Error::new("the `issuer-url` field should be specified"))?
.ok_or_else(|| warn!("the `issuer-url` field should be specified"))?
.parse()
.map(IssuerUrl::from_url)?;
let mut client = if let Some(jwks_url) = config.get_str("jwks-url") {
let jwks_url = JsonWebKeySetUrl::new(jwks_url.to_owned())?;
let jwks = JsonWebKeySet::fetch(&jwks_url, http_client)?;
let auth_url = config
.get_str("auth-url")
.ok_or_else(|| Error::new("the `auth-url` field should be specified"))?
.ok_or_else(|| warn!("the `auth-url` field should be specified"))?
.parse()
.map(AuthUrl::from_url)?;
let token_url = config
Expand Down
4 changes: 2 additions & 2 deletions zino-core/src/auth/security_token.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use self::ParseSecurityTokenError::*;
use super::AccessKeyId;
use crate::{crypto, datetime::DateTime, encoding::base64, error::Error};
use crate::{crypto, datetime::DateTime, encoding::base64, error::Error, warn};
use std::{fmt, time::Duration};

/// Security token.
Expand Down Expand Up @@ -66,7 +66,7 @@ impl SecurityToken {
pub(crate) fn parse_with(token: String, key: &[u8]) -> Result<Self, ParseSecurityTokenError> {
let authorization = base64::decode(&token).map_err(|err| DecodeError(err.into()))?;
let signature = crypto::decrypt(&authorization, key)
.map_err(|_| DecodeError(Error::new("fail to decrypt authorization")))?;
.map_err(|_| DecodeError(warn!("fail to decrypt authorization")))?;
let signature_str = String::from_utf8_lossy(&signature);
if let Some((access_key_id, timestamp)) = signature_str.split_once(':') {
let timestamp = timestamp
Expand Down
6 changes: 4 additions & 2 deletions zino-core/src/auth/user_session.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use super::{AccessKeyId, JwtClaims, SessionId};
use crate::{application::APP_DOMAIN, crypto::Digest, error::Error, extension::JsonObjectExt};
use crate::{
application::APP_DOMAIN, crypto::Digest, error::Error, extension::JsonObjectExt, warn,
};
use std::str::FromStr;

/// Role-based user sessions.
Expand Down Expand Up @@ -103,7 +105,7 @@ where
.subject()
.map(|s| s.into())
.or_else(|| data.parse_string("uid"))
.ok_or_else(|| Error::new("the subject of a JWT token should be specified"))?
.ok_or_else(|| warn!("the subject of a JWT token should be specified"))?
.parse()?;
let mut user_session = Self::new(user_id, None);
if let Some(roles) = data
Expand Down
5 changes: 2 additions & 3 deletions zino-core/src/chatbot/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use self::ChatbotClient::*;
use super::ChatbotService;
use crate::{error::Error, extension::TomlTableExt, Map};
use crate::{bail, error::Error, extension::TomlTableExt, Map};
use toml::Table;

#[cfg(feature = "chatbot-openai")]
Expand Down Expand Up @@ -46,8 +46,7 @@ impl Chatbot {
#[cfg(feature = "chatbot-openai")]
"openai" => OpenAiChatCompletion::try_new_chatbot(config),
_ => {
let message = format!("chatbot service `{service}` is unsupported");
Err(Error::new(message))
bail!("chatbot service `{}` is unsupported", service);
}
}
}
Expand Down
32 changes: 14 additions & 18 deletions zino-core/src/connector/connector_arrow/arrow_array.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{encoding::base64, error::Error, AvroValue, JsonValue, Map};
use crate::{bail, encoding::base64, error::Error, warn, AvroValue, JsonValue, Map};
use apache_avro::{Days, Duration, Millis, Months};
use datafusion::arrow::{
array::{self, Array, ArrayAccessor, FixedSizeBinaryArray, FixedSizeListArray, StringArray},
Expand Down Expand Up @@ -219,8 +219,7 @@ impl ArrowArrayExt for dyn Array {
hashmap.insert(key, value);
} else {
let key_type = map_array.key_type();
let message = format!("Avro map does not support `{key_type}` keys ");
return Err(Error::new(message));
bail!("Avro map does not support `{}` keys", key_type);
}
}
AvroValue::Map(hashmap)
Expand All @@ -246,10 +245,10 @@ impl ArrowArrayExt for dyn Array {
.position(|(ty, _)| type_id == ty)
.ok_or_else(|| {
let type_names = union_array.type_names();
let message = format!(
"invalid slot `{type_id}` for the union types `{type_names:?}`"
);
Error::new(message)
warn!(
"invalid slot `{}` for the union types `{:?}`",
type_id, type_names
)
})?;
let value = union_array.value(index).parse_avro_value(0)?;
AvroValue::Union(position.try_into()?, Box::new(value))
Expand All @@ -261,16 +260,15 @@ impl ArrowArrayExt for dyn Array {
let dictionary_array = array::as_dictionary_array::<UInt32Type>(self);
let string_array = dictionary_array
.downcast_dict::<StringArray>()
.ok_or_else(|| Error::new("fail to downcast the dictionary to string array"))?;
.ok_or_else(|| warn!("fail to downcast the dictionary to string array"))?;
let value = string_array.value(index);
let position = dictionary_array.lookup_key(value).ok_or_else(|| {
Error::new(format!("value `{value}` is not in the dictionary"))
})?;
let position = dictionary_array
.lookup_key(value)
.ok_or_else(|| warn!("value `{}` is not in the dictionary", value))?;
AvroValue::Enum(position, value.to_owned())
}
data_type => {
let message = format!("cannot convert the `{data_type}` value to an Avro value");
return Err(Error::new(message));
bail!("cannot convert the `{}` value to an Avro value", data_type);
}
};
Ok(value)
Expand Down Expand Up @@ -384,8 +382,7 @@ impl ArrowArrayExt for dyn Array {
map.insert(key, value);
} else {
let key_type = map_array.key_type();
let message = format!("json object does not support `{key_type}` keys ");
return Err(Error::new(message));
bail!("json object does not support `{}` keys", key_type);
}
}
JsonValue::Object(map)
Expand All @@ -410,13 +407,12 @@ impl ArrowArrayExt for dyn Array {
let dictionary_array = array::as_dictionary_array::<UInt32Type>(self);
let string_array = dictionary_array
.downcast_dict::<StringArray>()
.ok_or_else(|| Error::new("fail to downcast the dictionary to string array"))?;
.ok_or_else(|| warn!("fail to downcast the dictionary to string array"))?;
let value = string_array.value(index);
JsonValue::String(value.to_owned())
}
data_type => {
let message = format!("cannot convert the `{data_type}` value to a json value");
return Err(Error::new(message));
bail!("cannot convert the `{}` value to a json value", data_type);
}
};
Ok(value)
Expand Down
5 changes: 2 additions & 3 deletions zino-core/src/connector/connector_arrow/arrow_field.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{error::Error, extension::AvroRecordExt, AvroValue, Record};
use crate::{bail, error::Error, extension::AvroRecordExt, AvroValue, Record};
use datafusion::arrow::{
array::{
self, Array, BinaryArray, BooleanArray, Float32Array, Float64Array, Int32Array, Int64Array,
Expand Down Expand Up @@ -28,8 +28,7 @@ impl ArrowFieldExt for Field {
AvroValue::Bytes(_) => DataType::Binary,
AvroValue::String(_) | AvroValue::Uuid(_) => DataType::Utf8,
_ => {
let message = format!("fail to construct an Arrow field for the `{field}` field");
return Err(Error::new(message));
bail!("fail to construct an Arrow field for the `{}` field", field);
}
};
Ok(Field::new(field, data_type, true))
Expand Down
9 changes: 4 additions & 5 deletions zino-core/src/connector/connector_arrow/arrow_schema.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::ArrowFieldExt;
use crate::{error::Error, Record, TomlValue};
use crate::{bail, error::Error, Record, TomlValue};
use datafusion::arrow::{
array::Array,
datatypes::{DataType, Field, Schema, UnionFields, UnionMode},
Expand Down Expand Up @@ -59,14 +59,14 @@ impl ArrowSchemaExt for Schema {
}
DataType::Union(UnionFields::new(positions, fields), UnionMode::Dense)
} else {
return Err(Error::new(format!("schema for `{key}` should be nonempty")));
bail!("schema for `{}` should be nonempty", key);
}
}
TomlValue::Table(table) => {
let schema = Self::try_from_toml_table(table)?;
DataType::Struct(schema.fields)
}
_ => return Err(Error::new(format!("schema for `{key}` is invalid"))),
_ => bail!("schema for `{}` is invalid", key),
};
fields.push(Field::new(name, data_type, true));
}
Expand Down Expand Up @@ -99,8 +99,7 @@ fn parse_arrow_data_type(value_type: &str) -> Result<DataType, Error> {
"bytes" => DataType::Binary,
"string" => DataType::Utf8,
_ => {
let message = format!("parsing `{value_type}` as Arrow data type is unsupported");
return Err(Error::new(message));
bail!("parsing `{}` as Arrow data type is unsupported", value_type);
}
};
Ok(data_type)
Expand Down
14 changes: 6 additions & 8 deletions zino-core/src/connector/connector_arrow/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
use super::{Connector, DataSource, DataSourceConnector::Arrow};
use crate::{
application::{http_client, PROJECT_DIR},
bail,
error::Error,
extension::TomlTableExt,
helper, Map, Record,
helper, warn, Map, Record,
};
use datafusion::{
arrow::{datatypes::Schema, record_batch::RecordBatch},
Expand Down Expand Up @@ -116,10 +117,10 @@ impl ArrowConnector {
for table in tables.iter().filter_map(|v| v.as_table()) {
let data_type = table
.get_str("type")
.ok_or_else(|| Error::new("the `type` field should be a str"))?;
.ok_or_else(|| warn!("the `type` field should be a str"))?;
let table_name = table
.get_str("name")
.ok_or_else(|| Error::new("the `name` field should be a str"))?;
.ok_or_else(|| warn!("the `name` field should be a str"))?;
let table_path = if let Some(url) = table.get_str("url") {
let table_file_path = root.join(format!("{table_name}.{data_type}"));
let mut table_file = File::create(&table_file_path)?;
Expand All @@ -132,9 +133,7 @@ impl ArrowConnector {
table
.get_str("path")
.map(|path| root.join(path).to_string_lossy().into_owned())
.ok_or_else(|| {
Error::new(format!("the path for the table `{table_name}` is absent"))
})?
.ok_or_else(|| warn!("the path for the table `{}` is absent", table_name))?
};
let table_schema = if let Some(schema) = table.get_table("schema") {
Some(Schema::try_from_toml_table(schema)?)
Expand Down Expand Up @@ -206,8 +205,7 @@ impl ArrowConnector {
.await?;
}
_ => {
let message = format!("data type `{data_type}` is unsupported");
return Err(Error::new(message));
bail!("data type `{}` is unsupported", data_type);
}
}
}
Expand Down
Loading

0 comments on commit 3bf82de

Please sign in to comment.