Swift创建NSError对象

时间:2015-10-15 21:00:35

标签: ios swift nserror

我正在尝试创建一个错误对象以显示给用户。

let userInfo: [NSObject : AnyObject] = 
    [
    "NSLocalizedDescriptionKey" :  NSLocalizedString("Unauthorized", comment: ""),
    "NSLocalizedFailureReasonErrorKey" : NSLocalizedString("Unauthorized", comment: "")
    ]
let err = NSError(domain: "ShiploopHttpResponseErrorDomain", code: httpResponse.statusCode, userInfo: userInfo)
print("Error in Post: \(err.localizedDescription)")

不幸的是输出是:

Error in Post: The operation couldn’t be completed.(ShiploopHttpResponseErrorDomain error 401.) 

我希望能够向用户显示他应该激活他的帐户。任何想法??

3 个答案:

答案 0 :(得分:29)

看起来像你想要的(见字典键):

  

Swift 2

let userInfo: [NSObject : AnyObject] =
[
    NSLocalizedDescriptionKey :  NSLocalizedString("Unauthorized", value: "Please activate your account", comment: ""),
    NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unauthorized", value: "Account not activated", comment: "")
]
  

Swift 3

let userInfo: [AnyHashable : Any] =
            [
                NSLocalizedDescriptionKey :  NSLocalizedString("Unauthorized", value: "Please activate your account", comment: "") ,
                NSLocalizedFailureReasonErrorKey : NSLocalizedString("Unauthorized", value: "Account not activated", comment: "")
        ]

然后在swift 2或3中创建错误对象,如下所示:

let err = NSError(domain: "ShiploopHttpResponseErrorDomain", code: 401, userInfo: userInfo)
println("Error in Post: \(err.localizedDescription)")

NSLocalizedDescriptionKey和NSLocalizedFailureReasonErrorKey是全局String变量,以及userInfo字典中的键。这些值与您指定的值略有不同:

println(NSLocalizedDescriptionKey) //prints "NSLocalizedDescription"
println(NSLocalizedFailureReasonErrorKey) //prints "NSLocalizedFailureReason"

通过右键单击类(本例中为NSError)并在xcode中选择“Jump To Definition”来查看文档是一种很好的做法。各种问题都可以这样回答。 :)

答案 1 :(得分:21)

在Swift 3中创建一个非常简单的错误:

let error = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Object does not exist"])

答案 2 :(得分:10)

创建错误就像以下一行一样简单:

let error = NSError(domain: "com.example.error", code: 0, userInfo: [NSLocalizedDescriptionKey: "message"])

如果您需要其他堆栈跟踪信息,请使用以下方法:

func error(_ message: String, code: Int = 0, domain: String = "com.example.error", function: String = #function, file: String = #file, line: Int = #line) -> NSError {

    let functionKey = "\(domain).function"
    let fileKey = "\(domain).file"
    let lineKey = "\(domain).line"

    let error = NSError(domain: domain, code: code, userInfo: [
        NSLocalizedDescriptionKey: message,
        functionKey: function,
        fileKey: file,
        lineKey: line
    ])

    // Crashlytics.sharedInstance().recordError(error)

    return error
}

<强>用法:

let localizedErrorMessage: String = NSLocalizedString("Unauthorized", comment: "Account not activated")
let error = error(localizedErrorMessage)