示例工程 13-error-handling

13-error-handling/Sources/Ch13Demo/App.swift

swift · 1.8 KB

import Ch13Kit
 
@main
struct Ch13Demo {
    static func main() {
        do {
            let document = try DocumentLoader.load("notes.md")
            print("[13.1] 成功 = \(document.title)/\(document.body)")
        } catch {
            print("[13.1] 不可能到这里:\(error)")
        }
 
        do {
            _ = try DocumentLoader.load("/root/secret")
        } catch let error as LoadError {
            print("[13.1] 失败 = \(error)")
        } catch {
            print("[13.1] 其他错误")
        }
 
        switch DocumentLoader.loadResult("x.bad") {
        case .success(let document):
            print("[13.2] Result 成功 = \(document.title)")
        case .failure(let error):
            print("[13.2] Result 失败 = \(error)")
        }
 
        print("[13.3] try? 空路径 = \(DocumentLoader.loadOptional("") == nil)")
        print("[13.3] try? 正常 = \(DocumentLoader.loadOptional("ok.md")?.title ?? "nil")")
 
        let mapped = try? CleanupLab.mapValues(["1", "2", "3"], CleanupLab.parseInt)
        print("[13.4] rethrows 成功 = \(mapped.map(String.init) ?? "nil")")
        let failed = try? CleanupLab.mapValues(["1", "x"], CleanupLab.parseInt)
        print("[13.4] rethrows 失败 = \(failed.map(String.init) ?? "nil")")
 
        print("[13.5] 成功路径 = \(CleanupLab.loadWithCleanup("ok.md"))")
        print("[13.5] 失败路径 = \(CleanupLab.loadWithCleanup("/root/x"))")
 
        print(
            "[13.6] 类型化抛错 = \(TypedParser.reason(""))/\(TypedParser.reason("x"))/\(TypedParser.reason("3"))"
        )
        print("[13.6] parseOrZero = \(TypedParser.parseOrZero("x"))")
        print(
            "[13.6] MemoryLayout<Result<Int, LoadError>> = \(MemoryLayout<Result<Int, LoadError>>.size) 字节"
        )
        print("[13.6] MemoryLayout<LoadError> = \(MemoryLayout<LoadError>.size) 字节")
    }
}