ios Swift 创建 NSError 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33158462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:01:16  来源:igfitidea点击:

Swift creating NSError Object

iosswiftnserror

提问by Ehab Saifan

I am trying to create an error object to display to the user.

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

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)")

Unfortunately the output is:

不幸的是,输出是:

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

I want to be able to show to the user that he should activate his account. Any ideas??

我希望能够向用户表明他应该激活他的帐户。有任何想法吗??

回答by ProgrammierTier

Looks like you want (see dictionary keys):

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

Swift 2

斯威夫特 2

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

Swift 3

斯威夫特 3

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

Then create the error object in both swift 2 or 3 like this:

然后像这样在 swift 2 或 3 中创建错误对象:

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

NSLocalizedDescriptionKey and NSLocalizedFailureReasonErrorKey are global String variables, and the keys inside of the userInfo dictionary. The values are slightly different from what you specified:

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

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

I find it good practice to look at the documentation by right-clicking the class (NSError in this case) and selecting "Jump To Definition" within xcode. All kinds of questions can be answered this way. :)

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

回答by Josh O'Connor

Creating a very simple error in Swift 3:

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

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

回答by AamirR

Creating an error is as simple as following line:

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

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

If you need additional stack trace information, use following method:

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

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
}

Usage:

用法:

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