use error_support::{ErrorHandling, GetErrorHandling};
use remote_settings::RemoteSettingsError;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Error opening database: {0}")]
OpenDatabase(#[from] sql_support::open_database::Error),
#[error("Error executing SQL: {inner} (context: {context})")]
Sql {
inner: rusqlite::Error,
context: String,
},
#[error("Serialization error: {0}")]
Serialization(String),
#[error("Error from Remote Settings: {0}")]
RemoteSettings(#[from] RemoteSettingsError),
#[error("Remote settings record is missing an attachment (id: u64)")]
MissingAttachment(String),
#[error("Operation interrupted")]
Interrupted(#[from] interrupt_support::Interrupted),
#[error("SuggestStoreBuilder {0}")]
SuggestStoreBuilder(String),
}
impl Error {
fn sql(e: rusqlite::Error, context: impl Into<String>) -> Self {
Self::Sql {
inner: e,
context: context.into(),
}
}
}
impl From<rusqlite::Error> for Error {
fn from(e: rusqlite::Error) -> Self {
Self::sql(e, "<none>")
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Self::Serialization(e.to_string())
}
}
impl From<rmp_serde::decode::Error> for Error {
fn from(e: rmp_serde::decode::Error) -> Self {
Self::Serialization(e.to_string())
}
}
impl From<rmp_serde::encode::Error> for Error {
fn from(e: rmp_serde::encode::Error) -> Self {
Self::Serialization(e.to_string())
}
}
#[extend::ext(name=RusqliteResultExt)]
pub impl<T> Result<T, rusqlite::Error> {
fn with_context(self, context: &str) -> Result<T, Error> {
self.map_err(|e| Error::sql(e, context))
}
}
#[derive(Debug, thiserror::Error, uniffi::Error)]
#[non_exhaustive]
pub enum SuggestApiError {
#[error("Network error: {reason}")]
Network { reason: String },
#[error("Backoff")]
Backoff { seconds: u64 },
#[error("Interrupted")]
Interrupted,
#[error("Other error: {reason}")]
Other { reason: String },
}
impl GetErrorHandling for Error {
type ExternalError = SuggestApiError;
fn get_error_handling(&self) -> ErrorHandling<Self::ExternalError> {
match self {
Self::Interrupted(_) => ErrorHandling::convert(SuggestApiError::Interrupted),
Self::RemoteSettings(RemoteSettingsError::Network { reason }) => {
ErrorHandling::convert(SuggestApiError::Network {
reason: reason.clone(),
})
.log_warning()
}
Self::RemoteSettings(RemoteSettingsError::Backoff { seconds }) => {
ErrorHandling::convert(SuggestApiError::Backoff { seconds: *seconds })
.report_error("suggest-backoff")
}
_ => ErrorHandling::convert(SuggestApiError::Other {
reason: self.to_string(),
})
.report_error("suggest-unexpected"),
}
}
}