在swift 3中生成您自己的错误代码

时间:2016-11-18 07:59:07

标签: ios swift3 nsurlsession

我想要实现的是在swift 3中执行URLSession请求。我在一个单独的函数中执行此操作(以便不为GET和POST单独编写代码)并返回{{ 1}}并处理闭包的成功和失败。有点像这样 -

URLSessionDataTask

我不希望处理此函数中的错误条件,并希望使用响应代码生成错误,并返回此错误以在调用此函数的任何地方处理它。 任何人都可以告诉我该怎么做?或者这不是处理这种情况的“快速”方式吗?

10 个答案:

答案 0 :(得分:79)

在您的情况下,错误是您尝试生成Error实例。 Swift 3中的Error是一个可用于定义自定义错误的协议。此功能特别适用于在不同操作系统上运行的纯Swift应用程序。

在iOS开发中,NSError类仍然可用,并且符合Error协议。

因此,如果您的目的只是传播此错误代码,则可以轻松替换

var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)

var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)

否则,请检查 Sandeep Bhandari answer,了解如何创建自定义错误类型

答案 1 :(得分:56)

您可以使用以下值创建符合Swift LocalizedError协议的协议:

protocol OurErrorProtocol: LocalizedError {

    var title: String? { get }
    var code: Int { get }
}

这使我们能够像这样创建具体的错误:

struct CustomError: OurErrorProtocol {

    var title: String?
    var code: Int
    var errorDescription: String? { return _description }
    var failureReason: String? { return _description }

    private var _description: String

    init(title: String?, description: String, code: Int) {
        self.title = title ?? "Error"
        self._description = description
        self.code = code
    }
}

答案 2 :(得分:38)

您可以创建枚举来处理错误:)

enum RikhError: Error {
    case unknownError
    case connectionError
    case invalidCredentials
    case invalidRequest
    case notFound
    case invalidResponse
    case serverError
    case serverUnavailable
    case timeOut
    case unsuppotedURL
 }

然后在enum中创建一个方法来接收http响应代码并返回相应的错误:)

static func checkErrorCode(_ errorCode: Int) -> RikhError {
        switch errorCode {
        case 400:
            return .invalidRequest
        case 401:
            return .invalidCredentials
        case 404:
            return .notFound
        //bla bla bla
        default:
            return .unknownError
        }
    }

最后更新你的故障块以接受RikhError类型的单个参数:)

我有一个详细的教程,介绍如何使用Swift3将传统的基于Objective-C的面向对象的网络模型重构为现代的面向协议的模型https://learnwithmehere.blogspot.in看一下:)

希望有所帮助:)

答案 3 :(得分:27)

您应该使用NSError对象。

let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild access token"])

然后将NSError转换为Error对象

答案 4 :(得分:14)

实施LocalizedError:

struct StringError : LocalizedError
{
    var errorDescription: String? { return mMsg }
    var failureReason: String? { return mMsg }
    var recoverySuggestion: String? { return "" }
    var helpAnchor: String? { return "" }

    private var mMsg : String

    init(_ description: String)
    {
        mMsg = description
    }
}

请注意,简单地实现Error,例如,如其中一个答案中所述,将失败(至少在Swift 3中),并且调用localizedDescription将导致字符串"操作无法完成。 (.StringError错误1。)"

答案 5 :(得分:4)

我仍然认为Harry的答案是最简单且完整的,但是如果您需要更简单的答案,请使用:

struct AppError {
    let message: String

    init(message: String) {
        self.message = message
    }
}

extension AppError: LocalizedError {
    var errorDescription: String? { return message }
//    var failureReason: String? { get }
//    var recoverySuggestion: String? { get }
//    var helpAnchor: String? { get }
}

并像这样使用或测试它:

printError(error: AppError(message: "My App Error!!!"))

func print(error: Error) {
    print("We have an ERROR: ", error.localizedDescription)
}

答案 6 :(得分:1)

我知道您已经对答案感到满意,但如果您有兴趣知道正确的方法,那么这可能对您有所帮助。 我不希望将http响应错误代码与错误对象中的错误代码混在一起(混淆了?请继续阅读...)。

http响应代码是关于http响应的标准错误代码,用于定义收到响应时的一般情况,并且从1xx到5xx不等(例如200 OK,408请求超时,504网关超时等 - http://www.restapitutorial.com/httpstatuscodes.html)< / p>

NSError对象中的错误代码为对象描述的特定应用程序/产品/软件域的错误类型提供了非常具体的标识。例如,您的应用程序可能会使用1000作为&#34;抱歉,您不能在一天内多次更新此记录&#34;或说1001 for&#34;您需要管理员角色来访问此资源&#34; ...这些特定于您的域/应用程序逻辑。

对于非常小的应用程序,有时会合并这两个概念。但它们完全不同,因为你可以看到,非常重要的&amp;有助于设计和使用大型软件。

因此,有两种技术可以更好地处理代码:

1。完成回调将执行所有检查

completionHandler(data, httpResponse, responseError) 

2。您的方法决定成功和错误情况,然后调用相应的回调

if nil == responseError { 
   successCallback(data)
} else {
   failureCallback(data, responseError) // failure can have data also for standard REST request/response APIs
}

快乐编码:)

答案 7 :(得分:1)

protocol CustomError : Error {

    var localizedTitle: String
    var localizedDescription: String

}

enum RequestError : Int, Error {

    case badRequest         = 400
    case loginFailed        = 401
    case userDisabled       = 403
    case notFound           = 404
    case methodNotAllowed   = 405
    case serverError        = 500
    case noConnection       = -1009
    case timeOutError       = -1001

}

func anything(errorCode: Int) -> CustomError? {

      return RequestError(rawValue: errorCode)
}

答案 8 :(得分:1)

 let error = NSError(domain:"", code:401, userInfo:[ NSLocalizedDescriptionKey: "Invaild UserName or Password"]) as Error
            self.showLoginError(error)

创建一个NSError对象并将其类型转换为Error,然后在任何地方显示

private func showLoginError(_ error: Error?) {
    if let errorObj = error {
        UIAlertController.alert("Login Error", message: errorObj.localizedDescription).action("OK").presentOn(self)
    }
}

答案 9 :(得分:0)

详细信息

  • Xcode版本10.2.1(10E1001)
  • 雨燕5

解决应用中的错误的方法

import Foundation

enum AppError {
    case network(type: Enums.NetworkError)
    case file(type: Enums.FileError)
    case custom(errorDescription: String?)

    class Enums { }
}

extension AppError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .network(let type): return type.localizedDescription
            case .file(let type): return type.localizedDescription
            case .custom(let errorDescription): return errorDescription
        }
    }
}

// MARK: - Network Errors

extension AppError.Enums {
    enum NetworkError {
        case parsing
        case notFound
        case custom(errorCode: Int?, errorDescription: String?)
    }
}

extension AppError.Enums.NetworkError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .parsing: return "Parsing error"
            case .notFound: return "URL Not Found"
            case .custom(_, let errorDescription): return errorDescription
        }
    }

    var errorCode: Int? {
        switch self {
            case .parsing: return nil
            case .notFound: return 404
            case .custom(let errorCode, _): return errorCode
        }
    }
}

// MARK: - FIle Errors

extension AppError.Enums {
    enum FileError {
        case read(path: String)
        case write(path: String, value: Any)
        case custom(errorDescription: String?)
    }
}

extension AppError.Enums.FileError: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .read(let path): return "Could not read file from \"\(path)\""
            case .write(let path, let value): return "Could not write value \"\(value)\" file from \"\(path)\""
            case .custom(let errorDescription): return errorDescription
        }
    }
}

用法

//let err: Error = NSError(domain:"", code: 401, userInfo: [NSLocalizedDescriptionKey: "Invaild UserName or Password"])
let err: Error = AppError.network(type: .custom(errorCode: 400, errorDescription: "Bad request"))

switch err {
    case is AppError:
        switch err as! AppError {
        case .network(let type): print("Network ERROR: code \(type.errorCode), description: \(type.localizedDescription)")
        case .file(let type):
            switch type {
                case .read: print("FILE Reading ERROR")
                case .write: print("FILE Writing ERROR")
                case .custom: print("FILE ERROR")
            }
        case .custom: print("Custom ERROR")
    }
    default: print(err)
}