use std::fmt;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
Bind,
Serve,
InvalidConfig,
ShutdownTimeout,
MissingWorkloadToken,
NoApiKey,
NoTokenOrAuthUrl,
AuthorizationCallbackFailed,
AuthorizationTimedOut,
Service,
}
impl ErrorKind {
fn is_identity(self) -> bool {
matches!(
self,
Self::MissingWorkloadToken
| Self::NoApiKey
| Self::NoTokenOrAuthUrl
| Self::AuthorizationCallbackFailed
| Self::AuthorizationTimedOut
| Self::Service
)
}
}
pub struct Error {
kind: ErrorKind,
message: String,
source: Option<BoxError>,
}
impl Error {
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self { kind, message: message.into(), source: None }
}
#[cfg(any(feature = "runtime", feature = "identity"))]
pub(crate) fn with_source(mut self, source: impl Into<BoxError>) -> Self {
self.source = Some(source.into());
self
}
pub fn kind(&self) -> ErrorKind {
self.kind
}
#[cfg(feature = "runtime")]
pub(crate) fn hides_source(&self) -> bool {
self.kind.is_identity()
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = f.debug_struct("Error");
debug.field("kind", &self.kind).field("message", &self.message);
if self.kind.is_identity() {
debug.finish_non_exhaustive()
} else {
debug.field("source", &self.source).finish()
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_deref().map(|source| source as _)
}
}
#[cfg(all(test, feature = "runtime"))]
mod tests {
use std::error::Error as _;
use super::*;
#[test]
fn display_text_does_not_repeat_the_source() {
let cause = std::io::Error::other("address in use");
let error = Error::new(ErrorKind::Bind, "failed to bind 127.0.0.1:8080").with_source(cause);
assert_eq!(error.to_string(), "failed to bind 127.0.0.1:8080");
assert_eq!(error.source().map(ToString::to_string).as_deref(), Some("address in use"));
}
#[test]
fn debug_output_of_a_runtime_error_includes_its_source() {
let cause = std::io::Error::other("address in use");
let error = Error::new(ErrorKind::Bind, "failed to bind").with_source(cause);
let debug = format!("{error:?}");
assert!(debug.starts_with("Error { kind: Bind, message: \"failed to bind\", source: Some("), "{debug}");
assert!(debug.contains("address in use"), "{debug}");
}
}