Skip to main content

Errors

Every method in a Hybrid Object can throw an error using the language-default error throwing feature:

HybridMath.swift
class HybridMath : HybridMathSpec {
public func add(a: Double, b: Double) throws -> Double {
if a < 0 || b < 0 {
throw RuntimeError.error("Value cannot be negative!")
}
return a + b
}
}

Errors will be propagated upwards to JS and can be caught just like any other kind of error using try/catch:

`Math.add(...)`: Value cannot be negative!

Promise rejections

Promises can also be rejected using error throwing syntax on the native side:

HybridMath.swift
class HybridMath : HybridMathSpec {
public func add(a: Double, b: Double) throws -> Promise<Double> {
return Promise.async {
if a < 0 || b < 0 {
throw RuntimeError.error("Value cannot be negative!")
}
return a + b
}
}
}

Promise rejections are handled as usual using the .catch, or await/catch syntax in JS:

const math = // ...
try {
await math.add(-5, -1)
} catch (error) {
console.log(error)
}

Swift Errors

Due to a Swift compiler bug, Swift Hybrid Objects can currently not throw errors. Instead, they will raise a fatalError(..) which can only be seen if the app is running in Xcode (debugger). This should be fixed in the next Xcode version.