Repository Public
1//2// SP Chat iOS3// File: SPChat-iOS/Core/Networking/APIError.swift4// Description: One error type for every backend call, with the stable codes the server returns and readable French messages.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//910import Foundation1112struct APIError: Error, LocalizedError, Equatable, Sendable {13 enum Kind: Equatable, Sendable {14 /// The request never reached the server (offline, DNS, TLS, timeout). Nothing was sent.15 case network16 /// 401 `locked`: the session ended or was revoked.17 case locked18 /// 403 `reauth_required`: a passkey verification younger than 10 minutes is needed.19 case reauthRequired20 case rateLimited21 case cancelled22 case decoding23 case http24 }25 var kind: Kind26 var status: Int27 var code: String?28 var message: String2930 var errorDescription: String? { message }3132 static func network(offline: Bool) -> APIError {33 APIError(kind: .network, status: 0, code: "network", message: offline ? String(localized: "Hors ligne : la requête n’a pas été envoyée.") : String(localized: "Réseau indisponible : la requête n’a pas abouti."))34 }35 static let cancelled = APIError(kind: .cancelled, status: 0, code: "cancelled", message: String(localized: "Annulé"))36 static let locked = APIError(kind: .locked, status: 401, code: "locked", message: String(localized: "Session terminée"))37 static func decoding(_ detail: String) -> APIError {38 APIError(kind: .decoding, status: 0, code: "decoding", message: String(localized: "Réponse du serveur illisible."))39 }4041 /// Builds the error for a non-2xx response from its JSON body `{error, code}` when present.42 static func from(status: Int, data: Data, lockedHeader: Bool) -> APIError {43 struct Body: Decodable { var error: String?; var code: String? }44 let body = try? JSONDecoder().decode(Body.self, from: data)45 let message = body?.error ?? String(localized: "Erreur du serveur (HTTP \(status))")46 if status == 401 && (lockedHeader || body?.code == "locked") { return .locked }47 if status == 403 && body?.code == "reauth_required" { return APIError(kind: .reauthRequired, status: 403, code: "reauth_required", message: message) }48 if status == 429 { return APIError(kind: .rateLimited, status: 429, code: body?.code ?? "rate_limited", message: String(localized: "Trop de tentatives. Réessaie dans quelques minutes.")) }49 return APIError(kind: .http, status: status, code: body?.code, message: message)50 }5152 /// Maps a transport error. Cancellation stays distinguishable so callers never show it as a failure.53 static func from(_ error: Error, offline: Bool) -> APIError {54 if let e = error as? APIError { return e }55 if error is CancellationError { return .cancelled }56 if let u = error as? URLError {57 if u.code == .cancelled { return .cancelled }58 return .network(offline: offline || u.code == .notConnectedToInternet || u.code == .dataNotAllowed)59 }60 return .network(offline: offline)61 }62}63