From 811c8f23f3dd47cfdf7970d498aa1a37197fab81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20Gu=CC=88ndu=CC=88z?= Date: Thu, 5 Sep 2024 16:45:34 +0200 Subject: [PATCH] Add error wrapper type to conform any error type to IdentifiableError --- .../Presets/AnyIdentifiableError.swift | 34 +++++++++++++++++++ .../Presets/TelemetryDeck+Errors.swift | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 Sources/TelemetryClient/Presets/AnyIdentifiableError.swift diff --git a/Sources/TelemetryClient/Presets/AnyIdentifiableError.swift b/Sources/TelemetryClient/Presets/AnyIdentifiableError.swift new file mode 100644 index 0000000..0a897c1 --- /dev/null +++ b/Sources/TelemetryClient/Presets/AnyIdentifiableError.swift @@ -0,0 +1,34 @@ +import Foundation + +/// A generic wrapper that conforms any error to ``IdentifiableError``, exposing its `localizedDescription` as the `message`. +public struct AnyIdentifiableError: LocalizedError, IdentifiableError { + /// Unique identifier for the error, such as `TelemetryDeck.Session.started`. + public let id: String + + /// The underlying error being wrapped. + public let error: any Error + + /// Initializes with a given `id` and `error`. + /// - Parameters: + /// - id: Unique identifier for the error, such as `TelemetryDeck.Session.started`. + /// - error: The error to be wrapped. + public init(id: String, error: any Error) { + self.id = id + self.error = error + } + + /// Provides the localized description of the wrapped error. + public var errorDescription: String { + self.error.localizedDescription + } +} + +extension Error { + /// Wraps any caught error with an `id` for use with ``TelemetryDeck.signal(identifiableError:)``. + /// - Parameters: + /// - id: Unique identifier for the error, such as `TelemetryDeck.Session.started`. + /// - Returns: An ``AnyIdentifiableError`` instance wrapping the given error. + public func with(id: String) -> AnyIdentifiableError { + AnyIdentifiableError(id: id, error: self) + } +} diff --git a/Sources/TelemetryClient/Presets/TelemetryDeck+Errors.swift b/Sources/TelemetryClient/Presets/TelemetryDeck+Errors.swift index 7cc5329..5029436 100644 --- a/Sources/TelemetryClient/Presets/TelemetryDeck+Errors.swift +++ b/Sources/TelemetryClient/Presets/TelemetryDeck+Errors.swift @@ -39,7 +39,7 @@ public extension TelemetryDeck { /// Sends a telemetry signal indicating that an identifiable error has occurred. /// /// - Parameters: - /// - identifiableError: The error that conforms to `IdentifiableError`. + /// - identifiableError: The error that conforms to `IdentifiableError`. Conform any error type by calling `.with(id:)` on it. /// - category: The category of the error. Default is `.thrownException`. /// - parameters: Additional parameters to include with the signal. Default is an empty dictionary. /// - floatValue: An optional floating-point value to include with the signal. Default is `nil`.