Skip to content
Open
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
22 changes: 21 additions & 1 deletion Sources/OpenAPIRuntime/Conversion/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,20 @@ public struct Configuration: Sendable {
/// Custom XML coder for encoding and decoding xml bodies.
public var xmlCoder: (any CustomCoder)?

/// The handler for client-side errors.
///
/// This handler is invoked after a client error has been wrapped in a ``ClientError``.
/// Use this to add logging, monitoring, or analytics for client-side errors.
/// If `nil`, errors are thrown without additional handling.
public var clientErrorHandler: (any ClientErrorHandler)?

/// The handler for server-side errors.
///
/// This handler is invoked after a server error has been wrapped in a ``ServerError``.
/// Use this to add logging, monitoring, or analytics for server-side errors.
/// If `nil`, errors are thrown without additional handling.
public var serverErrorHandler: (any ServerErrorHandler)?

/// Creates a new configuration with the specified values.
///
/// - Parameters:
Expand All @@ -160,15 +174,21 @@ public struct Configuration: Sendable {
/// - jsonEncodingOptions: The options for the underlying JSON encoder.
/// - multipartBoundaryGenerator: The generator to use when creating mutlipart bodies.
/// - xmlCoder: Custom XML coder for encoding and decoding xml bodies. Only required when using XML body payloads.
/// - clientErrorHandler: Optional handler for observing client-side errors. Defaults to `nil`.
/// - serverErrorHandler: Optional handler for observing server-side errors. Defaults to `nil`.
public init(
dateTranscoder: any DateTranscoder = .iso8601,
jsonEncodingOptions: JSONEncodingOptions = [.sortedKeys, .prettyPrinted],
multipartBoundaryGenerator: any MultipartBoundaryGenerator = .random,
xmlCoder: (any CustomCoder)? = nil
xmlCoder: (any CustomCoder)? = nil,
clientErrorHandler: (any ClientErrorHandler)? = nil,
serverErrorHandler: (any ServerErrorHandler)? = nil
) {
self.dateTranscoder = dateTranscoder
self.jsonEncodingOptions = jsonEncodingOptions
self.multipartBoundaryGenerator = multipartBoundaryGenerator
self.xmlCoder = xmlCoder
self.clientErrorHandler = clientErrorHandler
self.serverErrorHandler = serverErrorHandler
}
}
54 changes: 54 additions & 0 deletions Sources/OpenAPIRuntime/Errors/ErrorHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import HTTPTypes

// MARK: - Client Error Handler

/// A protocol for observing and logging errors that occur during client operations.
///
/// Implement this protocol to add logging, monitoring, or analytics for client-side errors.
/// This handler is called after the error has been wrapped in a ``ClientError``, providing
/// full context about the operation and the error.
///
/// - Note: This handler should not throw or modify the error. Its purpose is observation only.
public protocol ClientErrorHandler: Sendable {
/// Called when a client error occurs, after it has been wrapped in a ``ClientError``.
///
/// Use this method to log, monitor, or send analytics about the error. The error
/// will be thrown to the caller after this method returns.
///
/// - Parameter error: The ``ClientError`` that will be thrown to the caller.
func handleClientError(_ error: ClientError)
}


// MARK: - Server Error Handler

/// A protocol for observing and logging errors that occur during server operations.
///
/// Implement this protocol to add logging, monitoring, or analytics for server-side errors.
/// This handler is called after the error has been wrapped in a ``ServerError``, providing
/// full context about the operation and the HTTP response that will be sent.
///
/// - Note: This handler should not throw or modify the error. Its purpose is observation only.
public protocol ServerErrorHandler: Sendable {
/// Called when a server error occurs, after it has been wrapped in a ``ServerError``.
///
/// Use this method to log, monitor, or send analytics about the error. The error
/// will be thrown to the error handling middleware after this method returns.
///
/// - Parameter error: The ``ServerError`` that will be thrown to the middleware.
func handleServerError(_ error: ServerError)
}
6 changes: 5 additions & 1 deletion Sources/OpenAPIRuntime/Interface/UniversalClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ import struct Foundation.URL
}
}
let baseURL = serverURL
let errorHandler = converter.configuration.clientErrorHandler
@Sendable func makeError(
request: HTTPRequest? = nil,
requestBody: HTTPBody? = nil,
Expand All @@ -112,6 +113,7 @@ import struct Foundation.URL
error.baseURL = error.baseURL ?? baseURL
error.response = error.response ?? response
error.responseBody = error.responseBody ?? responseBody
errorHandler?.handleClientError(error)
return error
}
let causeDescription: String
Expand All @@ -123,7 +125,7 @@ import struct Foundation.URL
causeDescription = "Unknown"
underlyingError = error
}
return ClientError(
let clientError = ClientError(
operationID: operationID,
operationInput: input,
request: request,
Expand All @@ -134,6 +136,8 @@ import struct Foundation.URL
causeDescription: causeDescription,
underlyingError: underlyingError
)
errorHandler?.handleClientError(clientError)
return clientError
}
let (request, requestBody): (HTTPRequest, HTTPBody?) = try await wrappingErrors {
try serializer(input)
Expand Down
6 changes: 5 additions & 1 deletion Sources/OpenAPIRuntime/Interface/UniversalServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,14 @@ import struct Foundation.URLComponents
throw mapError(error)
}
}
let errorHandler = converter.configuration.serverErrorHandler
@Sendable func makeError(input: OperationInput? = nil, output: OperationOutput? = nil, error: any Error)
-> any Error
{
if var error = error as? ServerError {
error.operationInput = error.operationInput ?? input
error.operationOutput = error.operationOutput ?? output
errorHandler?.handleServerError(error)
return error
}
let causeDescription: String
Expand Down Expand Up @@ -136,7 +138,7 @@ import struct Foundation.URLComponents
httpHeaderFields = [:]
httpBody = nil
}
return ServerError(
let serverError = ServerError(
operationID: operationID,
request: request,
requestBody: requestBody,
Expand All @@ -149,6 +151,8 @@ import struct Foundation.URLComponents
httpHeaderFields: httpHeaderFields,
httpBody: httpBody
)
errorHandler?.handleServerError(serverError)
return serverError
}
var next: @Sendable (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> (HTTPResponse, HTTPBody?) =
{ _request, _requestBody, _metadata in
Expand Down
134 changes: 134 additions & 0 deletions Tests/OpenAPIRuntimeTests/Errors/Test_ErrorHandler.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftOpenAPIGenerator open source project
//
// Copyright (c) 2025 Apple Inc. and the SwiftOpenAPIGenerator project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import HTTPTypes
@_spi(Generated) @testable import OpenAPIRuntime
import XCTest

// MARK: - Test Helpers

/// A custom client error handler that logs all errors for testing
final class LoggingClientErrorHandler: ClientErrorHandler {
var handledErrors: [ClientError] = []
private let lock = NSLock()

func handleClientError(_ error: ClientError) {
lock.lock()
handledErrors.append(error)
lock.unlock()
}
}

/// A custom server error handler that logs all errors for testing
final class LoggingServerErrorHandler: ServerErrorHandler {
var handledErrors: [ServerError] = []
private let lock = NSLock()

func handleServerError(_ error: ServerError) {
lock.lock()
handledErrors.append(error)
lock.unlock()
}
}

// MARK: - ErrorHandler Tests

final class Test_ErrorHandler: XCTestCase {

func testClientErrorHandler_IsCalledWithClientError() throws {
let handler = LoggingClientErrorHandler()
let clientError = ClientError(
operationID: "testOp",
operationInput: "test-input",
request: .init(soar_path: "/test", method: .get),
requestBody: nil,
baseURL: URL(string: "https://example.com"),
response: nil,
responseBody: nil,
causeDescription: "Test error",
underlyingError: NSError(domain: "test", code: 1)
)

handler.handleClientError(clientError)

XCTAssertEqual(handler.handledErrors.count, 1)
XCTAssertEqual(handler.handledErrors[0].operationID, "testOp")
XCTAssertEqual(handler.handledErrors[0].causeDescription, "Test error")
}

func testServerErrorHandler_IsCalledWithServerError() throws {
let handler = LoggingServerErrorHandler()
let serverError = ServerError(
operationID: "testOp",
request: .init(soar_path: "/test", method: .post),
requestBody: nil,
requestMetadata: .init(),
operationInput: "test-input",
operationOutput: nil,
causeDescription: "Test error",
underlyingError: NSError(domain: "test", code: 1),
httpStatus: .badRequest,
httpHeaderFields: [:],
httpBody: nil
)

handler.handleServerError(serverError)

XCTAssertEqual(handler.handledErrors.count, 1)
XCTAssertEqual(handler.handledErrors[0].operationID, "testOp")
XCTAssertEqual(handler.handledErrors[0].httpStatus, .badRequest)
}

func testMultipleErrors_AreAllLogged() throws {
let clientHandler = LoggingClientErrorHandler()
let serverHandler = LoggingServerErrorHandler()

// Log multiple client errors
for i in 1...3 {
let error = ClientError(
operationID: "op\(i)",
operationInput: nil as String?,
request: nil,
requestBody: nil,
baseURL: nil,
response: nil,
responseBody: nil,
causeDescription: "Error \(i)",
underlyingError: NSError(domain: "test", code: i)
)
clientHandler.handleClientError(error)
}

// Log multiple server errors
for i in 1...3 {
let error = ServerError(
operationID: "op\(i)",
request: .init(soar_path: "/test", method: .get),
requestBody: nil,
requestMetadata: .init(),
operationInput: nil as String?,
operationOutput: nil as String?,
causeDescription: "Error \(i)",
underlyingError: NSError(domain: "test", code: i),
httpStatus: .internalServerError,
httpHeaderFields: [:],
httpBody: nil
)
serverHandler.handleServerError(error)
}

XCTAssertEqual(clientHandler.handledErrors.count, 3)
XCTAssertEqual(serverHandler.handledErrors.count, 3)
}
}
Loading