Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing swift error with specific error type in method signature

With the new swift error handling introduced in 2.1 is it possible to specify a given ErrorType a method will throw?

e.g. class func nextOrderDate() throws OrderError -> NSDate {...}

like image 332
Julian B. Avatar asked Nov 04 '15 18:11

Julian B.


People also ask

How would you call a function that throws errors and also returns a value?

It's called rethrows . The rethrows keyword is used for functions that don't directly throw an error.

Do-catch with error?

Handling Errors Using Do-Catch. You use a do - catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it's matched against the catch clauses to determine which one of them can handle the error.

Can Call throw but is not marked with try?

Where is the Reachability type defined? Maybe it has a throw -ing default initializer? The issue is that the initializer you are using is marked with 'throws' which means that it can throw an exception when it encounters a problem.


1 Answers

In Swift, instead of throwing a specific type, you catch specific types, like this:

do {
   let date = try nextOrderDate() 
} catch let error as OrderError {
   print("OrderError")
} catch {
   print("other error")
}

A workaround that I have seen many times, is to return the error instead (very often seen in completion blocks):

class func nextOrderDate() -> (NSDate?, OrderError?)

SWIFT 5

You can now use:

class func nextOrderDate() -> Result<NSDate, OrderError>
like image 55
Daniel Avatar answered Oct 25 '22 07:10

Daniel