Create custom error in Swift

It's good to have good error handling. Errors are different for every project. It's good to define what can happen and attach fallback to let user know what went wrong. Lets how to do it in Swift

In Swift, you can create a custom error by defining an enumeration that conforms to the Error protocol. Here is an example:

enum CustomError: Error {
    case invalidInput
    case outOfBounds
}

You can then throw this custom error in a function or method:

func processData(data: Any) throws {
    guard let _ = data as? String else {
        throw CustomError.invalidInput
    }
    // continue with processing...
}

And handle it in a do-catch block:

do {
    try processData(data: "some data")
} catch CustomError.invalidInput {
    print("Invalid input provided")
} catch {
    print("Other error: \(error)")
}

You can also use your custom error in a try? or try! statement, but it's recommended to handle it explicitly in a do-catch block.

You can add a message property to the custom error enumeration to include additional information about the error. Here's an example:

enum CustomError: Error {
    case invalidInput(message: String)
    case outOfBounds(message: String)
}

You can then throw the custom error with a message:

func processData(data: Any) throws {
    guard let _ = data as? String else {
        throw CustomError.invalidInput(message: "Provided data is not a string")
    }
    // continue with processing...
}

And access the message in the catch block:

do {
    try processData(data: 123)
} catch CustomError.invalidInput(let message) {
    print("Invalid input provided: \(message)")
} catch {
    print("Other error: \(error)")
}

This will print "Invalid input provided: Provided data is not a string"

You can also add more properties to your error object to store more information.