Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ on:
jobs:
build:
name: ${{ matrix.platform }} on Xcode ${{ matrix.xcode }}
runs-on: macos-13
runs-on: macos-15
strategy:
matrix:
platform: [macOS, iOS, tvOS, watchOS]
xcode: [^14] # ^15
xcode: [^16]
steps:
- uses: actions/checkout@v4

Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,13 @@
## Unreleased

* Adds error reporting: `Aptabase.shared.trackError(error)` and `trackError(error, fatal: true)` post structured error reports (type, message, stack trace, severity, kind) to the `Errors` page https://github.com/aptabase/aptabase-swift/pull/39
* Error reports are sent immediately and retried from memory on network failures; 403 (monthly error quota exhausted) is never retried
* Stack traces are captured at the `trackError` call site with the SDK's own frames removed
* Report fields are truncated to the server's limits instead of being rejected
* Errors from Apple frameworks are reported by domain and code, Swift errors by type name with their description
* CI runs on `macos-15` with Xcode 16; the retired `macos-13` image left every run queued until timeout
* Fixes the build on Xcode 16 (Swift 6.1): `Dispatcher<Item>` cannot be used in a conformance clause there, so the dispatchers declare their `Item` typealias instead

## 0.3.12

* Adds an `appVersion` option to `InitOptions` to override the app version read from the bundle https://github.com/aptabase/aptabase-swift/pull/36
Expand Down
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,29 +112,32 @@ A few important notes:

> Error reporting is in beta. Reports appear on the `Errors` page of your Aptabase dashboard.

Use `.trackError()` to report errors you've caught and handled:
Use `trackError` to report errors you've caught and handled:

```swift
import Aptabase

do {
try someFailingFunction()
} catch {
Aptabase.shared.trackError(error)
Aptabase.shared.trackError(error) // severity: error
}
```

For errors your app can't recover from, mark the report as fatal:

```swift
.trackError(error, fatal: true); // severity: fatal
Aptabase.shared.trackError(error, fatal: true) // severity: fatal
```

A few important notes about error reporting:

1. Each report includes the error type, message, stack trace, severity (`error` or `fatal`) and how it was captured (`handled`, `unhandled` or `crash`).
2. Errors count against a separate monthly error quota. When the quota is exhausted, the server rejects new reports until it resets.

1. Each report includes the error type, message, stack trace, severity (`error` or `fatal`) and how it was captured (`handled`, or `crash` when `fatal` is set). Swift errors are reported under their type name with their description; errors from Apple frameworks (`NSError`, `URLError`, `CocoaError`) are grouped by domain and code, for example `NSURLErrorDomain -1009`.
2. The stack trace is captured where `trackError` is called, since Swift errors carry no stack of their own. The SDK's own frames are removed so the first frame is your call site.
3. Reports are sent immediately and kept in memory for retry when the network is unavailable (up to 25 pending reports). They are not persisted to disk, so a report may be lost if the app terminates right after `trackError` returns.
4. Fields longer than the server accepts (for example a 10,000 character stack trace) are truncated rather than rejected.
5. Errors count against a separate monthly error quota. When the quota is exhausted, the server rejects new reports until it resets.
6. Uncaught exceptions and crashes are not reported automatically yet. Call `trackError` from your own error handling.

## Preparing for Submission to Apple App Store

Expand Down
6 changes: 3 additions & 3 deletions Sources/Aptabase/Aptabase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public class Aptabase: NSObject {
/// Track errors you've caught and handled.
/// - Parameters:
/// - error: The error to report.
/// - fatal: Wether the app can recover from the error.
/// - fatal: Whether the app can recover from the error. Fatal errors are reported with severity `fatal` and kind `crash`.
public func trackError(_ error: Error, fatal: Bool = false) {
enqueueErrorReport(error, fatal: fatal)
}
Expand Down Expand Up @@ -108,9 +108,9 @@ public class Aptabase: NSObject {
/// Track errors you've caught and handled.
/// - Parameters:
/// - error: The error to report.
/// - fatal: Wether the app can recover from the error.
/// - fatal: Whether the app can recover from the error. Fatal errors are reported with severity `fatal` and kind `crash`.
@objc public func trackError(_ error: NSError, fatal: Bool = false) {
enqueueErrorReport(error, fatal: fatal)
enqueueErrorReport(error, fatal: fatal)
}

/// Forces all queued events to be sent to the server asynchronously. Returns before the events have been sent.
Expand Down
28 changes: 14 additions & 14 deletions Sources/Aptabase/AptabaseClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,8 @@ class AptabaseClient {
}

public func trackEvent(_ eventName: String, with props: [String: AnyCodableValue] = [:]) async {
let now = Date()
if lastTouched.distance(to: now) > AptabaseClient.sessionTimeout {
sessionId = AptabaseClient.newSessionId()
}
lastTouched = now

evaluateSessionId()

let evt = Event(timestamp: Date(),
sessionId: sessionId,
eventName: eventName,
Expand All @@ -60,19 +54,25 @@ class AptabaseClient {
await eventDispatcher.enqueue(evt)
}

/// Begins tracking an error asynchronously.
/// Begins tracking an error asynchronously. The stack trace is captured here, on the caller's
/// thread, so it points at the call site rather than at the task that delivers the report.
public func trackError(_ error: any Error, fatal: Bool = false) {
let stackTrace = ErrorReport.captureStackTrace()
Task {
await trackError(error, fatal: fatal)
await trackError(error, fatal: fatal, stackTrace: stackTrace)
}
}
public func trackError(_ error: any Error, fatal: Bool = false) async {

public func trackError(_ error: any Error, fatal: Bool = false, stackTrace: String? = nil) async {
evaluateSessionId()
let errorReport = ErrorReport.build(error, fatal: fatal, sessionId: sessionId, sdkVersion: AptabaseClient.sdkVersion, env: env)

let errorReport = ErrorReport.build(error, fatal: fatal, sessionId: sessionId, sdkVersion: AptabaseClient.sdkVersion, env: env, stackTrace: stackTrace)

await errorDispatcher.enqueue(errorReport)

// Errors are high-value: attempt delivery right away instead of waiting for the next
// poll tick. Failures stay queued for the regular flushes.
await errorDispatcher.flush()
}

public func startPolling() {
Expand Down
45 changes: 19 additions & 26 deletions Sources/Aptabase/Dispatcher.swift
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
//
// File.swift
// Aptabase
//
// Created by Joshua Wolfson on 6/9/2026.
//

import Foundation

protocol URLSessionProtocol {
Expand All @@ -13,36 +6,36 @@ protocol URLSessionProtocol {

extension URLSession: URLSessionProtocol {}


protocol Dispatcher<Item>: Actor where Item: Encodable {
associatedtype Item

var maximumBatchSize: Int { get }
var queue: ConcurrentQueue<Item> { get set }
var apiUrl: URL { get }
var headers: [String: String] { get }
var session: URLSessionProtocol { get }

var encoder: JSONEncoder { get }

func enqueue(_ newItem: Item)

func enqueue(_ newItems: [Item])

func flush() async

func sendItems(_ items: [Item]) async throws

init(appKey: String, baseUrl: String, env: EnvironmentInfo, session: URLSessionProtocol)
}

extension Dispatcher {
func enqueue(_ newItem: Item) {
queue.enqueue(newItem)
}

func enqueue(_ newItems: [Item]) {
queue.enqueue(contentsOf: newItems)
}

func flush() async {
if queue.isEmpty {
return
Expand All @@ -64,14 +57,14 @@ extension Dispatcher {
}
}

extension Dispatcher {
var encoder: JSONEncoder {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(identifier: "UTC")
encoder.dateEncodingStrategy = .formatted(formatter)
return encoder
}
/// One encoder per dispatcher: building the date formatter is comparatively expensive, so it must
/// not happen per request.
func makeDispatcherEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
formatter.locale = Locale(identifier: "en_US")
formatter.timeZone = TimeZone(identifier: "UTC")
encoder.dateEncodingStrategy = .formatted(formatter)
return encoder
}
118 changes: 61 additions & 57 deletions Sources/Aptabase/ErrorDispatcher.swift
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
//
// File.swift
// Aptabase
//
// Created by Joshua Wolfson on 5/9/2026.
//

import Foundation

// Errors have their own dispatcher because the error endpoint takes a single object per request and has different retry semantics than the events endpoint: 408/429 must be retried, while 403 (monthly error quota exhausted) must never be retried.
public actor ErrorDispatcher: Dispatcher<ErrorReport> {
internal var queue = ConcurrentQueue<ErrorReport>()
internal let maximumBatchSize = 1
internal let headers: [String: String]
internal let apiUrl: URL
internal let session: URLSessionProtocol

private let maximumQueueSize: Int = 25

// Errors have their own dispatcher because the error endpoint takes a single object per request and
// has different retry semantics than the events endpoint: 408/429 must be retried, while 403
// (monthly error quota exhausted) must never be retried.
actor ErrorDispatcher: Dispatcher {
typealias Item = ErrorReport

var queue = ConcurrentQueue<ErrorReport>()
let maximumBatchSize = 1
let headers: [String: String]
let apiUrl: URL
let session: URLSessionProtocol
let encoder = makeDispatcherEncoder()

// Max number of unsent reports kept in memory. New reports are dropped when full, so the first
// occurrences (closest to the root cause) are kept.
private let maximumQueueSize = 25

init(appKey: String, baseUrl: String, env: EnvironmentInfo, session: URLSessionProtocol = URLSession.shared) {
self.session = session
apiUrl = URL(string: "\(baseUrl)/api/v0/error")!
Expand All @@ -26,55 +26,59 @@ public actor ErrorDispatcher: Dispatcher<ErrorReport> {
"User-Agent": "\(env.osName)/\(env.osVersion) \(env.locale)"
]
}

func enqueue(_ report: ErrorReport) {
if queue.count >= maximumQueueSize {
debugPrint("Aptabase: Error report queue is full. Dropping report.")
return
}
enqueue([report])
}

queue.enqueue(report)
func enqueue(_ reports: [ErrorReport]) {
let capacity = max(0, maximumQueueSize - queue.count)
if reports.count > capacity {
debugPrint("Aptabase: Error report queue is full. Dropping \(reports.count - capacity) report(s).")
}
queue.enqueue(contentsOf: Array(reports.prefix(capacity)))
}

func sendItems(_ items: [ErrorReport]) async throws {
// only send the first error report
guard let errorReport = items.first else {
return
}
// the error endpoint takes one report per request
guard let errorReport = items.first else {
return
}

do {
let body = try encoder.encode(errorReport)
do {
let body = try encoder.encode(errorReport)

var request = URLRequest(url: apiUrl)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = body
var request = URLRequest(url: apiUrl)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = body

let (data, response) = try await session.data(for: request)
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
if statusCode < 300 {
return
}
let (data, response) = try await session.data(for: request)
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
if statusCode < 300 {
return
}

let responseText = String(data: data, encoding: .utf8) ?? ""
let reason = "\(statusCode) \(responseText)"

// The server reports an exhausted monthly error quota as 403
if statusCode == 403 {
debugPrint("Aptabase: Error report rejected because of \(reason). Will not retry.")
return
}
let responseText = String(data: data, encoding: .utf8) ?? ""
let reason = "\(statusCode) \(responseText)"

if statusCode == 408 || statusCode == 429 || statusCode >= 500 {
debugPrint("Aptabase: Failed to send error report because of \(reason). Will retry later.")
throw NSError(domain: "AptabaseError", code: statusCode, userInfo: ["reason": reason])
}
// The server reports an exhausted monthly error quota as 403 (not 429) precisely so
// clients drop the report instead of retrying it
if statusCode == 403 {
debugPrint("Aptabase: Error report rejected because of \(reason). Will not retry.")
return
}

debugPrint("Aptabase: Failed to send error report because of \(reason). Will not retry.")
return
} catch {
debugPrint("Aptabase: Failed to send error report. Reason: \(error)")
throw error
}
if statusCode == 408 || statusCode == 429 || statusCode >= 500 {
debugPrint("Aptabase: Failed to send error report because of \(reason). Will retry later.")
throw NSError(domain: "AptabaseError", code: statusCode, userInfo: ["reason": reason])
}

debugPrint("Aptabase: Failed to send error report because of \(reason). Will not retry.")
return
} catch {
debugPrint("Aptabase: Failed to send error report. Reason: \(error)")
throw error
}
}
}
Loading
Loading