use crate::errors::ErrorCode;
use time::OffsetDateTime;
#[derive(Debug, Clone)]
pub struct ErrorEvent {
pub app_name: String,
pub error_code: ErrorCode,
pub message: String,
pub location: String,
pub timestamp: OffsetDateTime,
pub source_error: Option<String>,
pub stacktrace: Option<String>,
pub request_url: Option<String>,
pub request_method: Option<String>,
pub user_id: Option<String>,
pub user_email: Option<String>,
pub tags: Option<serde_json::Value>,
pub extra: Option<serde_json::Value>,
pub breadcrumbs: Option<serde_json::Value>,
pub fingerprint: Option<String>,
}
impl ErrorEvent {
pub fn new(
app_name: impl Into<String>,
error_code: ErrorCode,
message: impl Into<String>,
location: impl Into<String>,
) -> Self {
Self {
app_name: app_name.into(),
error_code,
message: message.into(),
location: location.into(),
timestamp: OffsetDateTime::now_utc(),
source_error: None,
stacktrace: None,
request_url: None,
request_method: None,
user_id: None,
user_email: None,
tags: None,
extra: None,
breadcrumbs: None,
fingerprint: None,
}
}
pub fn with_source_error(mut self, source: impl Into<String>) -> Self {
self.source_error = Some(source.into());
self
}
pub fn with_stacktrace(mut self, stacktrace: impl Into<String>) -> Self {
self.stacktrace = Some(stacktrace.into());
self
}
pub fn with_request(mut self, method: impl Into<String>, url: impl Into<String>) -> Self {
self.request_method = Some(method.into());
self.request_url = Some(url.into());
self
}
pub fn with_user(mut self, user_id: impl Into<String>) -> Self {
self.user_id = Some(user_id.into());
self
}
pub fn with_user_email(
mut self,
user_id: impl Into<String>,
email: impl Into<String>,
) -> Self {
self.user_id = Some(user_id.into());
self.user_email = Some(email.into());
self
}
pub fn with_tags(mut self, tags: serde_json::Value) -> Self {
self.tags = Some(tags);
self
}
pub fn with_extra(mut self, extra: serde_json::Value) -> Self {
self.extra = Some(extra);
self
}
pub fn with_breadcrumbs(mut self, breadcrumbs: serde_json::Value) -> Self {
self.breadcrumbs = Some(breadcrumbs);
self
}
pub fn with_fingerprint(mut self, fingerprint: impl Into<String>) -> Self {
self.fingerprint = Some(fingerprint.into());
self
}
pub fn severity(&self) -> &'static str {
match self.error_code {
ErrorCode::Database => "critical",
ErrorCode::Exception => "major",
ErrorCode::Authentication | ErrorCode::Authorization => "minor",
ErrorCode::BadRequest | ErrorCode::NotFound | ErrorCode::Validation => "warning",
}
}
}