ios 在 Swift 2 中使用自定义消息抛出错误/异常的最简单方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31443645/
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
Simplest way to throw an error/exception with a custom message in Swift 2?
提问by markdb314
I want to do something in Swift 2 that I'm used to doing in multiple other languages: throw a runtime exception with a custom message. For example (in Java):
我想在 Swift 2 中做一些我习惯于用其他多种语言做的事情:用自定义消息抛出运行时异常。例如(在 Java 中):
throw new RuntimeException("A custom message here")
I understand that I can throw enum types that conform to the ErrorType protocol, but I don't want to have to define enums for every type of error I throw. Ideally, I'd like to be able mimic the example above as closely as possible. I looked into creating a custom class that implements the ErrorType protocol, but I can't even figure out that what that protocol requires (see documentation). Ideas?
我知道我可以抛出符合 ErrorType 协议的枚举类型,但我不想为我抛出的每种类型的错误定义枚举。理想情况下,我希望能够尽可能地模仿上面的例子。我考虑创建一个实现 ErrorType 协议的自定义类,但我什至无法弄清楚该协议需要什么(请参阅文档)。想法?
回答by Arkku
The simplest approach is probably to define onecustom enum
with just one case
that has a String
attached to it:
最简单的方法可能是定义一个定制的enum
只有一个case
是有一个String
连接到它:
enum MyError: ErrorType {
case runtimeError(String)
}
Or, as of Swift 4:
或者,从 Swift 4 开始:
enum MyError: Error {
case runtimeError(String)
}
Example usage would be something like:
示例用法类似于:
func someFunction() throws {
throw MyError.runtimeError("some message")
}
do {
try someFunction()
} catch MyError.runtimeError(let errorMessage) {
print(errorMessage)
}
If you wish to use existing Error
types, the most general one would be an NSError
, and you could make a factory method to create and throw one with a custom message.
如果您希望使用现有Error
类型,最常用的是 an NSError
,您可以创建一个工厂方法来创建并抛出一个带有自定义消息的类型。
回答by Nick Keets
The simplest way is to make String
conform to Error
:
最简单的方法是使String
符合Error
:
extension String: Error {}
Then you can just throw a string:
然后你可以抛出一个字符串:
throw "Some Error"
To make the string itself be the localizedString
of the error you can instead extend LocalizedError
:
要使字符串本身成为localizedString
错误,您可以改为扩展LocalizedError
:
extension String: LocalizedError {
public var errorDescription: String? { return self }
}
回答by Alexander Borisenko
@nick-keets's solution is most elegant, but it did break down for me in test target with the following compile time error:
@nick-keets 的解决方案是最优雅的,但它确实在测试目标中崩溃了,并出现以下编译时错误:
Redundant conformance of 'String' to protocol 'Error'
Redundant conformance of 'String' to protocol 'Error'
Here's another approach:
这是另一种方法:
struct RuntimeError: Error {
let message: String
init(_ message: String) {
self.message = message
}
public var localizedDescription: String {
return message
}
}
And to use:
并使用:
throw RuntimeError("Error message.")
回答by Teodor Ciuraru
Check this cool version out. The idea is to implement both String and ErrorType protocols and use the error's rawValue.
看看这个很酷的版本。这个想法是实现 String 和 ErrorType 协议并使用错误的 rawValue。
enum UserValidationError: String, Error {
case noFirstNameProvided = "Please insert your first name."
case noLastNameProvided = "Please insert your last name."
case noAgeProvided = "Please insert your age."
case noEmailProvided = "Please insert your email."
}
Usage:
用法:
do {
try User.define(firstName,
lastName: lastName,
age: age,
email: email,
gender: gender,
location: location,
phone: phone)
}
catch let error as User.UserValidationError {
print(error.rawValue)
return
}
回答by PJ_Finnegan
Swift 4:
斯威夫特 4:
As per:
按照:
https://developer.apple.com/documentation/foundation/nserror
https://developer.apple.com/documentation/foundation/nserror
if you don't want to define a custom exception, you could use a standard NSError object as follows:
如果您不想定义自定义异常,则可以使用标准 NSError 对象,如下所示:
import Foundation
do {
throw NSError(domain: "my error description", code: 42, userInfo: ["ui1":12, "ui2":"val2"] )
}
catch let error as NSError {
print("Caught NSError: \(error.localizedDescription), \(error.domain), \(error.code)")
let uis = error.userInfo
print("\tUser info:")
for (key,value) in uis {
print("\t\tkey=\(key), value=\(value)")
}
}
Prints:
印刷:
Caught NSError: The operation could not be completed, my error description, 42
User info:
key=ui1, value=12
key=ui2, value=val2
This allows you to provide a custom string, plus a numeric code and a dictionary with all the additional data you need, of any type.
这允许您提供一个自定义字符串、一个数字代码和一个包含您需要的任何类型的所有附加数据的字典。
N.B.: this was tested on OS=Linux (Ubuntu 16.04 LTS).
注意:这是在 OS=Linux (Ubuntu 16.04 LTS) 上测试的。
回答by Vyachaslav Gerchicov
Simplest solution without extra extensions, enums, classes and etc.:
最简单的解决方案,无需额外的扩展、枚举、类等:
NSException(name:NSExceptionName(rawValue: "name"), reason:"reason", userInfo:nil).raise()
回答by Roney Sampaio
In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError:
fatalError ("Custom message here")
如果您不需要捕获错误并且想立即停止应用程序,您可以使用致命错误:
fatalError ("Custom message here")
回答by eonist
Based on @Nick keets answer, here is a more complete example:
基于@Nick keets 的回答,这里有一个更完整的例子:
extension String: Error {} // Enables you to throw a string
extension String: LocalizedError { // Adds error.localizedDescription to Error instances
public var errorDescription: String? { return self }
}
func test(color: NSColor) throws{
if color == .red {
throw "I don't like red"
}else if color == .green {
throw "I'm not into green"
}else {
throw "I like all other colors"
}
}
do {
try test(color: .green)
} catch let error where error.localizedDescription == "I don't like red"{
Swift.print ("Error: \(error)") // "I don't like red"
}catch let error {
Swift.print ("Other cases: Error: \(error.localizedDescription)") // I like all other colors
}
Originally published on my swift blog: http://eon.codes/blog/2017/09/01/throwing-simple-errors/
最初发表在我的 swift 博客上:http: //eon.codes/blog/2017/09/01/throwing-simple-errors/
回答by Benjamin Smith
I like @Alexander-Borisenko's answer, but the localized description was not returned when caught as an Error. It seems that you need to use LocalizedError instead:
我喜欢@Alexander-Borisenko 的回答,但是当被捕获为错误时,本地化的描述没有返回。似乎您需要使用 LocalizedError 来代替:
struct RuntimeError: LocalizedError
{
let message: String
init(_ message: String)
{
self.message = message
}
public var errorDescription: String?
{
return message
}
}
See this answerfor more details.
有关更多详细信息,请参阅此答案。