问题
JavascriptCore permits us to expose our Objective-C classes to javascript via the JSExport protocol. Let's say, in one of the exposed Objective-C class's methods, a condition is encountered where it makes sense to raise an exception. Is there a way to create said exception and raise it such that the javascript code can process it as it would process a regular javascript exception?
I tried doing a regular old [NSException raise...]
and that immediately caused a crash.
Am I relegated to detecting the raise condition, passing that condition back to javascript, and having the javascript do the throw?
回答1:
Objective-C JSContext
object have exception property, that may be used to throw an exception to JavaScript. According comments in header file:
Before a callback is made from JavaScript to an Objective-C block or method, the prior value of the exception property will be preserved and the property will be set to nil. After the callback has completed the new value of the exception property will be read, and prior value restored. If the new value of exception is not nil, the callback will result in that value being thrown.
来源:https://stackoverflow.com/questions/29979041/raising-an-exception-from-objective-c-back-to-javascript