How to declare network Error with enum in Swift

Issue #712

Describe all possible paths in your program with enum. This is great to track down bugs and to not miss representing potential cases in UI. Errors can come from app layer, backend layer to network issues.

Enum is handy in both UIKit and SwiftUI

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
enum NetworkError: Swift.Error {
enum RequestError {
case invalidRequest(URLRequest)
case encodingError(Swift.EncodingError)
case other(NSError)
}

enum ServerError {
case decodingError(Swift.DecodingError)
case noInternetConnection
case timeout
case internalServerError
case other(statusCode: Int, response: HTTPURLResponse)
}

case requestError(RequestError)
case serverError(ServerError)
}

and note that Foundation has NSError with a bunch of well defined error code ready to use. We can use this before introduce our custom error cases

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public var NSURLErrorUnknown: Int { get }
public var NSURLErrorCancelled: Int { get }
public var NSURLErrorBadURL: Int { get }
public var NSURLErrorTimedOut: Int { get }
public var NSURLErrorUnsupportedURL: Int { get }
public var NSURLErrorCannotFindHost: Int { get }
public var NSURLErrorCannotConnectToHost: Int { get }
public var NSURLErrorNetworkConnectionLost: Int { get }
public var NSURLErrorDNSLookupFailed: Int { get }
public var NSURLErrorHTTPTooManyRedirects: Int { get }
public var NSURLErrorResourceUnavailable: Int { get }
public var NSURLErrorNotConnectedToInternet: Int { get }
public var NSURLErrorRedirectToNonExistentLocation: Int { get }
public var NSURLErrorBadServerResponse: Int { get }
public var NSURLErrorUserCancelledAuthentication: Int { get }
public var NSURLErrorUserAuthenticationRequired: Int { get }
public var NSURLErrorZeroByteResource: Int { get }
public var NSURLErrorCannotDecodeRawData: Int { get }
public var NSURLErrorCannotDecodeContentData: Int { get }
public var NSURLErrorCannotParseResponse: Int { get }

Comments