forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSException.swift
More file actions
58 lines (53 loc) · 2.12 KB
/
JSException.swift
File metadata and controls
58 lines (53 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/// `JSException` is a wrapper that handles exceptions thrown during JavaScript execution as Swift
/// `Error` objects.
/// When a JavaScript function throws an exception, it's wrapped as a `JSException` and propagated
/// through Swift's error handling mechanism.
///
/// Example:
/// ```swift
/// do {
/// try jsFunction.throws()
/// } catch let error as JSException {
/// // Access the value thrown from JavaScript
/// let jsErrorValue = error.thrownValue
/// }
/// ```
public struct JSException: Error, Equatable, CustomStringConvertible {
/// The value thrown from JavaScript.
/// This can be any JavaScript value (error object, string, number, etc.).
public var thrownValue: JSValue {
return _thrownValue
}
/// The actual JavaScript value that was thrown.
///
/// Marked as `nonisolated(unsafe)` to satisfy `Sendable` requirement
/// from `Error` protocol.
private nonisolated(unsafe) let _thrownValue: JSValue
/// A description of the exception.
public let description: String
/// The stack trace of the exception.
public let stack: String?
/// Initializes a new JSException instance with a value thrown from JavaScript.
///
/// Only available within the package. This must be called on the thread where the exception object created.
@usableFromInline
package init(_ thrownValue: JSValue) {
self._thrownValue = thrownValue
// Capture the stringified representation on the object owner thread
// to bring useful info to the catching thread even if they are different threads.
if let errorObject = thrownValue.object, let stack = errorObject.stack.string {
self.description = "JSException(\(stack))"
self.stack = stack
} else {
self.description = "JSException(\(thrownValue))"
self.stack = nil
}
}
/// Initializes a new JavaScript `Error` instance with a message and prepare it to be thrown.
///
/// - Parameters:
/// - message: The message to throw.
public init(message: String) {
self.init(JSError(message: message).jsValue)
}
}