Errors
Implementation
Enum based
The simplest approach is probably to define one custom enum with just one case that has a String attached to it:
enum MyError: Error {
case runtimeError(String)
}
extension MyError: LocalizedError {
var errorDescription: String? {
switch self {
case .runtimeError(let str):
"RunTime Error: \(str)"
}
}
}
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.
Struct based
Or use another approach
struct RuntimeError: LocalizedError {
let description: String
init(_ description: String) {
self.description = description
}
var errorDescription: String? {
description
}
}
And to use:
throw RuntimeError("Error message.")
Mind Map
Error Handling
SO | generate-your-own-error-code-in-swift
References
apple dev | errors and exceptions
apple archive | error handling guide
NS Error
Information about an error condition including a domain, a domain-specific error code, and application-specific information.
Exception
Use
NSExceptionto implement exception handling. An exception is a special condition that interrupts the normal flow of program execution. Each application can interrupt the program for different reasons. For example, one application might interpret saving a file in a directory that is write-protected as an exception. In this sense, the exception is equivalent to an error. Another application might interpret the user’s key-press (for example, Control-C) as an exception: an indication that a long-running process should abort.