示例工程 13-error-handling

13-error-handling/Sources/Ch13Kit/Loader.swift

swift · 1.6 KB

/// 可恢复错误用枚举表达;遵循 `Error` 即可被 `throw` / `catch`。
public enum LoadError: Error, Equatable, CustomStringConvertible {
    case notFound(String)
    case denied(String)
    case corrupted(line: Int)
 
    public var description: String {
        switch self {
        case .notFound(let path):
            return "notFound(\(path))"
        case .denied(let path):
            return "denied(\(path))"
        case .corrupted(let line):
            return "corrupted(line:\(line))"
        }
    }
}
 
public struct Document: Equatable, Sendable {
    public let title: String
    public let body: String
 
    public init(title: String, body: String) {
        self.title = title
        self.body = body
    }
}
 
public enum DocumentLoader {
    public static func load(_ path: String) throws -> Document {
        guard !path.isEmpty else { throw LoadError.notFound(path) }
        guard !path.hasPrefix("/root") else { throw LoadError.denied(path) }
        guard !path.hasSuffix(".bad") else { throw LoadError.corrupted(line: 3) }
        return Document(title: path, body: "hello")
    }
 
    /// `Result` 把成功与失败都变成值,适合回调与异步边界。
    public static func loadResult(_ path: String) -> Result<Document, LoadError> {
        do {
            return .success(try load(path))
        } catch let error as LoadError {
            return .failure(error)
        } catch {
            return .failure(.corrupted(line: 0))
        }
    }
 
    /// `try?` 丢弃原因,只保留「有没有成功」。
    public static func loadOptional(_ path: String) -> Document? {
        try? load(path)
    }
}