summaryrefslogtreecommitdiff
path: root/Hutch/Networking/SRHTError.swift
blob: f148c001902b15867968433126a5ff04dd3eddbf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import Foundation

/// Errors produced by the Sourcehut GraphQL client.
enum SRHTError: LocalizedError, Sendable {
    /// The server returned one or more GraphQL-level errors.
    case graphQLErrors([GraphQLError])
    /// The HTTP response had a non-2xx status code.
    case httpError(Int)
    /// The response data could not be decoded.
    case decodingError(any Error)
    /// A networking error from URLSession (timeout, DNS, connectivity, etc.).
    case networkError(any Error)
    /// 401 or no authentication token configured.
    case unauthorized

    var errorDescription: String? {
        switch self {
        case .graphQLErrors(let errors):
            let messages = errors.map(\.message).joined(separator: "\n")
            return "GraphQL error: \(messages)"
        case .httpError(let code):
            return "Server returned HTTP \(code)."
        case .decodingError(let error):
            return "Failed to decode response: \(error.localizedDescription)"
        case .networkError(let error):
            return "Network error: \(error.localizedDescription)"
        case .unauthorized:
            return "Authentication required. Please sign in again."
        }
    }

    /// Whether this error represents a connectivity issue (no internet, timeout, DNS).
    var isConnectivityError: Bool {
        switch self {
        case .networkError(let error):
            let nsError = error as NSError
            let connectivityCodes: Set<Int> = [
                NSURLErrorNotConnectedToInternet,
                NSURLErrorNetworkConnectionLost,
                NSURLErrorTimedOut,
                NSURLErrorCannotFindHost,
                NSURLErrorCannotConnectToHost,
                NSURLErrorDNSLookupFailed,
                NSURLErrorInternationalRoamingOff,
                NSURLErrorDataNotAllowed
            ]
            return connectivityCodes.contains(nsError.code)
        default:
            return false
        }
    }
}

/// A single error entry from the GraphQL `errors` array.
struct GraphQLError: Decodable, Sendable {
    let message: String
    let locations: [GraphQLErrorLocation]?
}

struct GraphQLErrorLocation: Decodable, Sendable {
    let line: Int
    let column: Int
}