In C# there is the empty throw (wich many programmers forget about and use throw error losing the real exception callstack).
I know that in Swift the context is not the same, but I'm thinking about something like that. A keyword called rethrow (to match the other pair: throws and rethrows) that simply rethrows the error captured in the catch statement.
(If Swift already has equivalent functionally, please enlighten me.)
I know this doesn't handle all possible cases where rethrow might be used, but in your given example you can write this in current Swift:
do {
try self.requestSomething()
} catch RequestError.failed(statusCode: 404) {
self.doSomethingElse()
} catch let error {
throw error
}
... which is an incredibly elegant solution to the problem. You can even drop the 'let error' from the final catch statement if you want even more brevity. I find most error-handling situations in my own code can be dealt with in similar ways to this.
@bzamayo Good catch! (No pun intended.) I think that in your example the catch let error can be omitted at all, leaving just the catch RequestError.failed(statusCode: 404). Am I right?
Not quite. The Swift error pattern matching model has a weird quirk where it binds a variable error in the catch all case where you specify no pattern. So this is valid code: