Xử lý Lỗi Một Cách Duyên dáng trong Swift: Xây dựng Ứng dụng iOS Vững vàng

Thông báo lỗi tệ nhất là thông báo chẳng ai đọc được: “The operation couldn’t be completed. (NSURLErrorDomain error -1009.)” không nói gì cho người dùng, cũng không nói gì cho bạn. Đó là dấu hiệu lỗi bị bắt ở tầng sai rồi ném lại nguyên dạng.

Xử lý lỗi trong Swift không bắt đầu bằng do-catch, mà bằng câu hỏi: tầng nào sở hữu thất bại này và tầng nào được phép biết chi tiết? Bên dưới: mô hình lỗi của Swift 6.4, service layer dùng typed throws, và ViewModel biến lỗi thành UI state.

Cập nhật 2026

  • Swift 6.4.2 (6.4 ra 15/09/2026), Xcode 27.2, iOS 27.2; typed throws (SE-0413) đủ chín cho biên service.
  • Swift 6 language mode: error type qua ranh giới actor phải Sendable; enum với payload String/Int đã thoả.
  • SE-0493: await trong defer chạy xong trước khi thoát scope. SE-0504 withTaskCancellationShield giữ cleanup chạy khi task bị huỷ.
  • SE-0522 @diagnose siết warning thành error theo từng khai báo.

Lỗi trong Swift là giá trị, không phải exception

Error là marker protocol, không thuộc tính, không method; bạn gần như luôn định nghĩa nó bằng enum vì tập lỗi phải hữu hạn. throws nằm trong chữ ký hàm nên là hợp đồng: caller buộc viết try.

Swift không có stack unwinding như Java hay C#. Lỗi là đường trả về thứ hai, và defer thay finally. Các mệnh đề catch chạy theo thứ tự, catch trần đứng cuối; rethrows dành cho wrapper chỉ ném lại lỗi từ closure.

Chọn công cụ: Optional, throws, Result hay typed throws

Một tiêu chí: caller cần thông tin gì để quyết định?

Tình huống Dùng Đánh đổi
Không có giá trị là bình thường: nickname chưa đặt, cache miss Optional Không có lý do thất bại
Thất bại cần lý do, cần phản ứng khác nhau throws Error type bị xoá thành any Error
Kết quả phải lưu, so sánh hoặc truyền qua callback Result Không lan truyền; phải switch ở mọi nơi
Tập lỗi đóng ở một biên module throws(E) Khó dùng với protocol, generic, closure

Mặc định là throws. Optional chỉ khi “không có” là kết quả hợp lệ; Result khi outcome là dữ liệu, ví dụ ViewModel giữ kết quả lần tải trước. Đừng bọc mọi thứ trong Result: bạn mất try ở call site, phải switch hai nhánh ở mọi nơi, và Result(catching:) còn trả Failure là any Error.

Typed throws: xử lý lỗi trong Swift 6 chặt hơn

throws(LoginError) khai báo tập lỗi đóng: throw phải đúng kiểu, caller biết kiểu, và switch không cần nhánh dự phòng.

// File: Sources/Auth/AuthService.swift
enum LoginError: Error, Equatable, Sendable {
    case invalidCredentials
    case locked(until: Date)
}

func login(user: String, password: String) async throws(LoginError) -> Session {
    guard !user.isEmpty, !password.isEmpty else { throw .invalidCredentials }
    throw .locked(until: Date().addingTimeInterval(600))
}

func signIn() async throws(LoginError) -> Session {
    do {
        return try await login(user: "an", password: "secret")
    } catch {
        throw error        // `error` là LoginError, không phải any Error
    }
}

Giới hạn: protocol requirement phải khớp đúng kiểu; generic và closure mang error type riêng nên khó ép. Biên hệ thống — URLSession, JSONDecoder — vẫn ném any Error, nên typed throws chỉ có nghĩa nếu bạn map một lần tại đó.

Lợi ích thật là không rò rỉ: DecodingError, URLError mã -1009 hay NSError từ SDK không nên xuất hiện trong UI hay public API.

Error protocol và custom error

Enum error mang ngữ cảnh bằng associated value; cho nó Equatable để test và Sendable để qua actor. Đừng nhét câu tiếng Việt vào error — copy UI thuộc tầng presentation.

// File: Sources/Core/APIError.swift
enum APIError: Error, Equatable, Sendable {
    case offline
    case transport(Transport)
    case http(status: Int, requestID: String?)
    case unauthorized
    case notFound
    case rateLimited(retryAfter: TimeInterval?)
    case decoding
    case cancelled

    enum Transport: Equatable, Sendable {
        case timeout
        case connectionLost
        case tls
        case other(code: Int)
    }
}

extension APIError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .offline: "Không có kết nối mạng."
        case .unauthorized: "Phiên đăng nhập đã hết hạn."
        case .notFound: "Không tìm thấy dữ liệu."
        default: "Không thể hoàn tất yêu cầu."
        }
    }
}

LocalizedError cấp localizedDescription cho log và alert hệ thống; đừng dùng nó làm nguồn copy UI vì thiếu trạng thái hành động.

Service layer: typed throws ở biên

Service là nơi duy nhất biết URLSession và JSONDecoder; ra ngoài chỉ có APIError. Hàm map là cửa duy nhất cho lỗi lạ.

// File: Sources/Core/ProfileService.swift
struct Profile: Decodable, Identifiable, Sendable {
    let id: UUID
    let displayName: String
}

struct ProfileService: Sendable {
    private let session: URLSession
    private let baseURL: URL

    init(baseURL: URL, session: URLSession = .shared) {
        self.baseURL = baseURL
        self.session = session
    }

    func profile(id: UUID) async throws(APIError) -> Profile {
        var request = URLRequest(url: baseURL.appendingPathComponent("v1/profiles/\(id)"))
        request.timeoutInterval = 15

        do {
            let (data, response) = try await session.data(for: request)
            guard let http = response as? HTTPURLResponse else {
                throw APIError.transport(.other(code: -1))
            }
            switch http.statusCode {
            case 200...299:
                do {
                    return try JSONDecoder().decode(Profile.self, from: data)
                } catch {
                    throw APIError.decoding
                }
            case 401, 403:
                throw APIError.unauthorized
            case 404:
                throw APIError.notFound
            case 429:
                let delay = http.value(forHTTPHeaderField: "Retry-After").flatMap { Double($0) }
                throw APIError.rateLimited(retryAfter: delay)
            default:
                throw APIError.http(status: http.statusCode,
                                    requestID: http.value(forHTTPHeaderField: "X-Request-ID"))
            }
        } catch {
            throw APIError.map(error)
        }
    }

    func profileResult(id: UUID) async -> Result<Profile, APIError> {
        do {
            return .success(try await profile(id: id))
        } catch {
            return .failure(APIError.map(error))
        }
    }
}
// File: Sources/Core/APIError+Mapping.swift
extension APIError {
    static func map(_ error: any Error) -> APIError {
        switch error {
        case let apiError as APIError: return apiError
        case let urlError as URLError:
            switch urlError.code {
            case .timedOut: return .transport(.timeout)
            case .notConnectedToInternet, .networkConnectionLost: return .offline
            case .cancelled: return .cancelled
            case .secureConnectionFailed, .serverCertificateUntrusted: return .transport(.tls)
            default: return .transport(.other(code: urlError.code.rawValue))
            }
        case is DecodingError: return .decoding
        case is CancellationError: return .cancelled
        default: return .transport(.other(code: -1))
        }
    }
}

profileResult dành cho chỗ giữ outcome như dữ liệu — cache, test; luồng UI dùng try await dễ đọc hơn.

ViewModel: map lỗi thành UI state

ViewModel không hiển thị lỗi, nó chọn state: đang tải, có dữ liệu, có lỗi kèm hành động. Lỗi huỷ khôi phục state trước, không tạo state thứ tư.

// File: Sources/Features/Profile/ProfileViewModel.swift
@MainActor
@Observable
final class ProfileViewModel {
    enum State {
        case idle
        case loading
        case loaded(Profile)
        case failed(ErrorPresentation)
    }

    private(set) var state: State = .idle
    private let service: ProfileService

    init(service: ProfileService) { self.service = service }

    func load(id: UUID) async {
        let previous = state
        state = .loading
        do {
            let profile = try await withRetry { try await service.profile(id: id) }
            state = .loaded(profile)
        } catch {
            guard let presentation = ErrorPresenter.present(APIError.map(error)) else {
                state = previous      // bị huỷ: không phải lỗi, không hiện alert
                return
            }
            state = .failed(presentation)
        }
    }
}

previous giữ nội dung cũ khi refresh rồi rời màn hình; nhánh .cancelled trong present trả nil.

// File: Sources/Features/Profile/ErrorPresentation.swift
struct ErrorPresentation: Equatable {
    let title: String
    let message: String
    let canRetry: Bool
}

enum ErrorPresenter {
    static func present(_ error: APIError) -> ErrorPresentation? {
        switch error {
        case .cancelled: return nil
        case .offline:
            return ErrorPresentation(title: "Không có kết nối",
                message: "Kiểm tra Wi-Fi hoặc dữ liệu di động rồi thử lại.", canRetry: true)
        case .transport(.timeout), .rateLimited:
            return ErrorPresentation(title: "Chưa tải được dữ liệu",
                message: "Thử lại sau vài giây.", canRetry: true)
        case .unauthorized:
            return ErrorPresentation(title: "Phiên đăng nhập hết hạn",
                message: "Đăng nhập lại để tiếp tục.", canRetry: false)
        case .notFound:
            return ErrorPresentation(title: "Không tìm thấy hồ sơ",
                message: "Hồ sơ có thể đã bị xoá.", canRetry: false)
        case .http(let status, _):
            return ErrorPresentation(title: "Không tải được dữ liệu",
                message: status >= 500 ? "Máy chủ đang gặp sự cố." : "Yêu cầu không hợp lệ.",
                canRetry: status >= 500)
        case .transport, .decoding:
            return ErrorPresentation(title: "Không tải được dữ liệu",
                message: "Kết nối bị gián đoạn. Thử lại nhé.", canRetry: true)
        }
    }
}

Copy ngắn, nói việc cần làm, không status code; cần hỗ trợ thì hiện X-Request-ID. Đưa các chuỗi này vào String Catalog để dịch.

// File: Sources/Features/Profile/ProfileScreen.swift
struct ProfileScreen: View {
    let model: ProfileViewModel
    let id: UUID

    var body: some View {
        Group {
            switch model.state {
            case .idle, .loading:
                ProgressView()
            case .loaded(let profile):
                Text(profile.displayName)
            case .failed(let presentation):
                ContentUnavailableView(presentation.title,
                    systemImage: "exclamationmark.triangle",
                    description: Text(presentation.message))
            }
        }
        .task(id: id) { await model.load(id: id) }
    }
}

.task(id:) huỷ task khi view biến mất, nên nhánh .cancelled chạy thường xuyên; không xử lý thì alert “Yêu cầu đã bị huỷ” hiện mỗi lần vuốt back.

try? và try!: hai cách im lặng

try? nén mọi lỗi thành nil, chỉ chấp nhận được khi có fallback rõ ràng: cache best-effort, dọn file tạm. Với network, nó biến “hết phiên” và “mất mạng” thành cùng một nil.

Ví dụ tệ nhất là try? await Task.sleep(for:) trong vòng retry: nó nuốt CancellationError, vòng lặp chạy tiếp sau khi task đã bị huỷ.

try! biến lỗi có thể phục hồi thành crash. Ngoại lệ duy nhất là bất biến bạn chứng minh được và compiler không thấy — file cấu hình trong bundle, fixture test; khi đó preconditionFailure còn hơn crash không lý do. Luồng network và JSON không có ngoại lệ.

Cancellation không phải lỗi thường

Ba nguồn huỷ: CancellationError từ Task.checkCancellation(), Task.sleep(for:), và URLError(.cancelled) từ URLSession. Cả ba nghĩa là “không còn ai cần kết quả”.

Map chúng về case riêng, không hiện UI lỗi, khôi phục state trước. Gộp vào catch trần rồi hiện “Đã xảy ra lỗi” thì thông báo hiện mỗi lần chuyển màn hình.

Cleanup vẫn dùng defer: Swift 6.4 cho phép await trong defer và bảo đảm nó chạy xong (SE-0493); withTaskCancellationShield (SE-0504) giữ cleanup chạy dù task đã bị huỷ. withTaskCancellationHandler dùng khi cần đóng connection ngay lúc có tín hiệu huỷ.

Retry và backoff: chỉ thử lại cái đáng thử

Retry là chính sách, không phải “gọi lại khi lỗi”: lỗi nào transient, bao nhiêu lần, chờ bao lâu, ai chịu trách nhiệm. Transient gồm timeout, mất kết nối, 5xx, 429. Không transient gồm 401/403, 404, lỗi decode và cancellation.

Backoff tăng theo cấp số nhân và có jitter, nếu không mọi client gọi lại cùng lúc. Tôn trọng Retry-After, và đừng retry POST không idempotent nếu API chưa có idempotency key.

// File: Sources/Core/Retry.swift
extension APIError {
    var isTransient: Bool {
        switch self {
        case .offline, .transport(.timeout), .transport(.connectionLost), .rateLimited:
            return true
        case .http(let status, _):
            return (500...599).contains(status)
        case .unauthorized, .notFound, .decoding, .cancelled, .transport(.tls), .transport(.other):
            return false
        }
    }

    var retryAfter: TimeInterval? {
        if case let .rateLimited(delay) = self { return delay }
        return nil
    }
}

func withRetry<T>(
    attempts: Int = 3,
    operation: () async throws(APIError) -> T
) async throws(APIError) -> T {
    var lastError = APIError.cancelled
    for attempt in 0..<attempts {
        if Task.isCancelled { throw .cancelled }
        do {
            return try await operation()
        } catch {
            lastError = APIError.map(error)
            guard lastError.isTransient, attempt < attempts - 1 else {
                throw lastError
            }
            let delay = lastError.retryAfter ?? backoffSeconds(attempt: attempt)
            do {
                try await Task.sleep(for: .seconds(delay))
            } catch {
                throw .cancelled
            }
        }
    }
    throw lastError
}

func backoffSeconds(attempt: Int, base: Double = 0.4) -> Double {
    let raw = min(8, base * pow(2, Double(attempt)))
    return raw + Double.random(in: 0...(raw / 2))
}

Đặt retry một chỗ — service hoặc decorator — không rải trong View. Retry trong nút bấm tạo một tầng retry mới mỗi lần bấm.

Logging: đủ để debug, không đủ để lộ PII

Dùng Logger của unified logging thay print. Chuỗi động mặc định private, nhưng số, bool và ngày mặc định public — log user id, số điện thoại hay số dư thì đánh dấu .private thủ công.

// File: Sources/Core/NetworkLog.swift
import OSLog

enum NetworkLog {
    static let logger = Logger(subsystem: "vn.evotek.profile", category: "network")

    static func failure(_ error: APIError, requestID: String, userID: UUID) {
        logger.error("request=\(requestID, privacy: .public) user=\(userID.uuidString, privacy: .private) kind=\(String(describing: error), privacy: .private)")
    }
}

Không log token, header Authorization, body, email hay URL có query. Log một lần ở biên service kèm X-Request-ID; chi tiết decode chỉ ở mức debug. .private không mã hoá — vẫn có thể lộ qua sysdiagnose.

Những lỗi thường gặp

  • Nuốt lỗi. catch { } rỗng hoặc try? hàng loạt làm UI kẹt ở loading. Sửa: mọi nhánh catch để lại dấu vết — state hoặc log.
  • try! trong luồng network/JSON. Crash thay vì thông báo. Sửa: do-catch và fallback có nghĩa.
  • Catch mọi thứ rồi báo “Đã xảy ra lỗi”. Không ai biết làm gì. Sửa: typed throws và switch theo case.
  • Đẩy lỗi server thô ra UI. Rò rỉ nội bộ, có thể chứa PII. Sửa: map sang tập copy nhỏ, giữ request id.
  • Dùng lỗi cho control flow. Validate form, “không có kết quả”, “chưa đăng nhập” là trạng thái. Sửa: trả enum hoặc giá trị rỗng.
  • Quên cancellation. Retry và alert vẫn chạy sau khi màn hình đã đóng.
  • print/localizedDescription làm copy UI. Log mất redaction, copy không dịch được. Sửa: Logger và ErrorPresenter.

Checklist trước khi merge

  • Mỗi hàm throws có error type rõ ràng; chỉ một hàm map dịch lỗi hệ thống.
  • Không còn try! trong luồng network, JSON, database.
  • .cancelled có nhánh riêng, không hiện alert, không đổi state thành failed.
  • Retry chỉ cho lỗi transient, có jitter, có giới hạn, tôn trọng Retry-After.
  • Log không chứa token, email, body; request id public; copy lỗi trong String Catalog.

Đọc tiếp trong lộ trình