Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JSError.stack, add Error conformance #48

Merged
merged 3 commits into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -401,4 +401,5 @@ try test("Error") {
try expectEqual(error.name, "Error")
try expectEqual(error.message, message)
try expectEqual(error.description, "Error: test error")
try expectEqual(error.stack?.isEmpty, false)
}
28 changes: 22 additions & 6 deletions Sources/JavaScriptKit/BasicObjects/JSError.swift
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
public final class JSError {
private let ref: JSObject
/** A wrapper around the [JavaScript Error
class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) that
exposes its properties in a type-safe way.
*/
public final class JSError: Error {
/// The underlying JavaScript `Error` object.
public let jsObject: JSObject

/// The constructor function used to create new `Error` objects.
private static let constructor = JSObject.global.Error.function!

/// Creates a new instance of the JavaScript `Error` class with a given message.
public init(message: String) {
ref = Self.constructor.new([message])
jsObject = Self.constructor.new([message])
}

/// The error message of the underlying `Error` object.
public var message: String {
ref.message.string!
jsObject.message.string!
}

/// The name (usually corresponds to the name of the underlying class) of a given error.
public var name: String {
ref.name.string!
jsObject.name.string!
}

/// The JavaScript call trace that led to the creation of this error object.
public var stack: String? {
jsObject.stack.string
}
}

extension JSError: CustomStringConvertible {
public var description: String { ref.description }
/// The textual representation of this error.
public var description: String { jsObject.description }
}