summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Extensions/CodingErrors+CustomErrorDescription.swift
blob: 4963298ba2723487f8d29b6eaf3dd2b48c90e2d3 (plain)
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
//
//  CodingErrors+CustomErrorDescription.swift
//  MullvadVPN
//
//  Created by pronebird on 17/02/2022.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import Foundation
import MullvadTypes

extension DecodingError: MullvadTypes.CustomErrorDescriptionProtocol {
    public var customErrorDescription: String? {
        switch self {
        case let .typeMismatch(type, context):
            return "Type mismatch, expected \(type) for key at \"\(context.codingPath.codingPathString)\"."

        case let .valueNotFound(_, context):
            return "Value not found at \"\(context.codingPath.codingPathString)\"."

        case let .keyNotFound(codingKey, context):
            return "Key \"\(codingKey.stringValue)\" not found at \"\(context.codingPath.codingPathString)\"."

        case .dataCorrupted:
            return "Data corrupted."

        @unknown default:
            return nil
        }
    }
}

extension EncodingError: MullvadTypes.CustomErrorDescriptionProtocol {
    public var customErrorDescription: String? {
        switch self {
        case let .invalidValue(_, context):
            return "Invalid value at \"\(context.codingPath.codingPathString)\""

        @unknown default:
            return nil
        }
    }
}

private extension [CodingKey] {
    var codingPathString: String {
        if isEmpty {
            return "<root>"
        } else {
            return map { $0.stringValue }
                .joined(separator: ".")
        }
    }
}