Swift 3 errors with additional data

后端 未结 1 834
盖世英雄少女心
盖世英雄少女心 2021-01-24 12:18

In Swift 3, what is the recommended way to put (potentially lots of) additional information in an error/exception that the catcher can use to solve/handle the problem? In all th

相关标签:
1条回答
  • 2021-01-24 13:04

    I don't know if there is a "recommended" way, perhaps someone else can answer that or provide a better solution.

    But one possible approach would be to use a struct (with properties) as the error type and use optional properties for values which need not be provided. Example:

    struct ParserError: Error {
        enum Reason {
            case invalidCharacter
            case unexpectedEOF
        }
        let reason: Reason
        let line: Int?
        let column: Int?
    
        init(reason: Reason, line: Int? = nil, column: Int? = nil) {
            self.reason = reason
            self.line = line
            self.column = column
        }
    }
    

    One might also want to adopt the LocalizedError protocol to provide sensible error descriptions even if the concrete error type is not known by the catcher (compare How to provide a localized description with an Error type in Swift?):

    extension ParserError: LocalizedError {
        public var errorDescription: String? {
            var description: String
            switch reason {
            case .invalidCharacter:
                description = "Invalid Character in input file"
            case .unexpectedEOF:
                description = "Unexpected end of file"
            }
            if let line = line {
                description += ", line \(line)"
            }
            if let column = column {
                description += ", column \(column)"
            }
            return description
        }
    }
    

    Usage example:

    func parse() throws {
        // Throw error with line number, but without column:
        throw ParserError(reason: .invalidCharacter, line: 13)
    }
    
    do {
        try parse()
    } catch let error {
        print(error.localizedDescription)
    }
    

    Output:

    Invalid Character in input file, line 13
    
    0 讨论(0)
提交回复
热议问题