美文网首页
Swift标准库解析:协议篇 - Error

Swift标准库解析:协议篇 - Error

作者: 灰s | 来源:发表于2017-12-11 15:59 被阅读0次

Error协议是用来进行错误处理的。
源码如下:

public protocol Error {
}

extension Error {
    //错误的本地化描述
    public var localizedDescription: String { get }
}

extension Error where Self.RawValue : SignedInteger {
}

extension Error where Self.RawValue : UnsignedInteger {
}

可以看到,标准库中只提供了一个localizedDescription只读属性,用来描述错误的具体信息。除此之外,并没有其他的方法。

Apple官方推荐使用枚举类型,具体说明如下。
Swift's enumerations are well suited to represent simple errors. Create an enumeration that conforms to the Error protocol with a case for each possible error. If there are additional details about the error that could be helpful for recovery, use associated values to include that information.

关于错误处理,我自己对这方面的了解的也不够深。这里我给大家介绍一下AlamofireAFError类,间接的来了解一下Error协议的用法。

定义

public enum AFError: Error {
    public enum ParameterEncodingFailureReason {
        case missingURL
        case jsonEncodingFailed(error: Error)
        case propertyListEncodingFailed(error: Error)
    }

    public enum MultipartEncodingFailureReason {
        case bodyPartURLInvalid(url: URL)
        case bodyPartFilenameInvalid(in: URL)
        case bodyPartFileNotReachable(at: URL)
        . . .
    }

    public enum ResponseValidationFailureReason {
        case dataFileNil
        case dataFileReadFailed(at: URL)
        case missingContentType(acceptableContentTypes: [String])
        . . .
    }

    public enum ResponseSerializationFailureReason {
        case inputDataNil
        case inputDataNilOrZeroLength
        case inputFileNil
        . . .
    }

    case invalidURL(url: URLConvertible)
    case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
    case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
    case responseValidationFailed(reason: ResponseValidationFailureReason)
    case responseSerializationFailed(reason: ResponseSerializationFailureReason)
}

每个case分别对应一种错误类型,并关联一个Reason
嵌套4个Reason枚举,来对错误的原因再次进行分类。不得不说代码很有逻辑感,也写的很好看。

错误描述

extension AFError.ParameterEncodingFailureReason {
    var localizedDescription: String {
        switch self {
        case .missingURL:
            return "URL request to encode was missing a URL"
        case .jsonEncodingFailed(let error):
            return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
        case .propertyListEncodingFailed(let error):
            return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)"
        }
    }
}

extension AFError.MultipartEncodingFailureReason {
    var localizedDescription: String {
        switch self {
        case .bodyPartURLInvalid(let url):
            return "The URL provided is not a file URL: \(url)"
        case .bodyPartFilenameInvalid(let url):
            return "The URL provided does not have a valid filename: \(url)"
        case .bodyPartFileNotReachable(let url):
            return "The URL provided is not reachable: \(url)"
        . . .
        }
    }
}

extension AFError.ResponseSerializationFailureReason {
    var localizedDescription: String {
        switch self {
        case .inputDataNil:
            return "Response could not be serialized, input data was nil."
        case .inputDataNilOrZeroLength:
            return "Response could not be serialized, input data was nil or zero length."
        case .inputFileNil:
            return "Response could not be serialized, input file was nil."
        . . .
        }
    }
}

extension AFError.ResponseValidationFailureReason {
    var localizedDescription: String {
        switch self {
        case .dataFileNil:
            return "Response could not be validated, data file was nil."
        case .dataFileReadFailed(let url):
            return "Response could not be validated, data file could not be read: \(url)."
        case .missingContentType(let types):
            return (
                "Response Content-Type was missing and acceptable content types " +
                "(\(types.joined(separator: ","))) do not match \"*/*\"."
            )
        . . .
        }
    }
}

使用localizedDescription属性,对每一个Reason的分支,进行详细的描述。

当然了,AFError并不是只有这些内容,还有很多方便我们使用的扩展等,由于它并不是我这篇文章的主要讨论方向,就不做更多介绍了。 有兴趣的可以去看看下面这个参考链接。
http://www.jianshu.com/p/99e6ba32f244

相关文章

网友评论

      本文标题:Swift标准库解析:协议篇 - Error

      本文链接:https://www.haomeiwen.com/subject/ijdlixtx.html