What are error handling patterns for URLSession in Swift?

When working with URLSession in Swift, handling errors effectively is crucial to creating robust applications. There are several error handling patterns that developers can use to manage networking errors efficiently.

Common Error Handling Patterns for URLSession

1. Try-Catch Blocks

Using try-catch blocks allows you to handle errors in an orderly fashion while making network requests.

2. Completion Handlers

By using completion handlers, you can pass errors back to the caller, enabling centralized error handling.

3. Result Type

Using Swift’s Result type can simplify error handling and make your code cleaner, allowing you to encapsulate the success or failure of a network call.

4. URLSessionDelegate

Implementing URLSessionDelegate can help to assess network errors and handle them appropiately during the session lifecycle events.

Example


    import Foundation

    func fetchData(from url: URL, completion: @escaping (Result) -> Void) {
        let session = URLSession.shared
        let task = session.dataTask(with: url) { data, response, error in
            if let error = error {
                completion(.failure(error)) // Handle error
                return
            }
            guard let data = data else {
                let error = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Data is nil"])
                completion(.failure(error))
                return
            }
            completion(.success(data)) // Success case
        }
        task.resume()
    }

    let url = URL(string: "https://api.example.com/data")!
    fetchData(from: url) { result in
        switch result {
        case .success(let data):
            // Handle successful data here
            print("Data received: \(data)")
        case .failure(let error):
            // Handle error here
            print("Error occurred: \(error)")
        }
    }
    

URLSession Swift error handling try-catch completion handlers Result type URLSessionDelegate