How to catch Foundation URLRequest errors

October 12, 2024 by Lou Zell

AIProxy uses Foundation's URL types such as URLRequest and URLSession for all connections from client to backend. Over the lifetime of a request, Foundation may raise any number of errors that your AIProxy integration code can choose to handle. Certain errors, like NSURLErrorTimedOut, NSURLErrorNetworkConnectionLost and NSURLErrorNotConnectedToInternet, may be worth catching to pop UI to your users.

See NSURLError.h for a list of errors that Foundation may raise. This file is easiest to find by punching cmd-shift-o into Xcode and searching for the name. Once you identify the errors that you're interested in, you can catch them in a try/catch structure:

import AIProxy

let openAIService = AIProxy.openAIService(
    partialKey: "partial-key-from-your-developer-dashboard",
    serviceURL: "service-url-from-your-developer-dashboard"
)

do {
    let response = try await openAIService.chatCompletionRequest(body: .init(
        model: "gpt-4o-mini",
        messages: [.assistant(content: .text("hello world"))]
    ))
    print(response.choices.first?.message.content ?? "")
}  catch AIProxyError.unsuccessfulRequest(let statusCode, let responseBody) {
    print("Received non-200 status code: \(statusCode) with response body: \(responseBody)")
} catch let err as URLError where err.code == URLError.timedOut {
    print("Request for OpenAI buffered chat completion timed out")
} catch let err as URLError where [.notConnectedToInternet, .networkConnectionLost].contains(err.code) {
    print("Could not make buffered chat request. Please check your internet connection")
} catch {
    print("Could not get buffered chat completion: \(error.localizedDescription)")
}