Section 8/91 menit

8. Migrasi dari Untyped Throws

8. Migrasi dari Untyped Throws

Strategi Bertahap

swift
// Langkah 1: Identifikasi semua error yang bisa dilempar
// Langkah 2: Buat enum yang mencakup semua kasus
// Langkah 3: Wrap existing throws ke typed throws

// SEBELUM:
func processPayment(amount: Double) throws -> Receipt {
    // bisa lempar: PaymentError, NetworkError, DatabaseError, ...
}

// SESUDAH — pendekatan pragmatis:
enum PaymentProcessingError: Error {
    case insufficientFunds(available: Double, required: Double)
    case cardDeclined(reason: String)
    case networkUnavailable
    case processingFailed(String)  // catch-all untuk yang tidak terduga
}

func processPayment(amount: Double) async throws(PaymentProcessingError) -> Receipt {
    do {
        let balance = try await checkBalance()
        guard balance >= amount else {
            throw PaymentProcessingError.insufficientFunds(available: balance, required: amount)
        }
        
        let receipt = try await chargeCard(amount: amount)
        try await saveReceipt(receipt)
        return receipt
        
    } catch let error as PaymentProcessingError {
        throw error  // re-throw typed
    } catch is URLError {
        throw PaymentProcessingError.networkUnavailable
    } catch {
        throw PaymentProcessingError.processingFailed(error.localizedDescription)
    }
}