WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: How do I know that URLSession.shared.data throws an Error in SwiftUI

Forums > Swift

Below code catches an Error object "error" when the server is not available:

    do{
        let (data, urlResponse) = try await URLSession.shared.data(for: request)
    } catch {
        print(error)
    }

When I read up on the documentation of URLSession.shared.data it is nowhere mentioned that it also throws an error (for URLSession.shared.dataTask for example it states explicitly that an error item is part of the returned values).

I mean the code is working but how would I KNOW that it returns an error object? That part is absolutely not transparent to me.

   

The method signature for URLSession.data(for:delegate:) looks like this:

func data(
    for request: URLRequest,
    delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse
)

See that throws in there? That's what tells you the method throws errors.

   

Thank you sir, makes sense! :)

   

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.