Skip to content

Commit d8e32e2

Browse files
authored
Merge pull request #397 from elixirscript/improve_erlang_error
erlang.error now throws errors resembling those in Elixir
2 parents 283c650 + 43af265 commit d8e32e2

File tree

3 files changed

+45
-2
lines changed

3 files changed

+45
-2
lines changed

src/javascript/lib/core/erlang_compat/erlang.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -478,7 +478,19 @@ function _throw(term) {
478478
}
479479

480480
function error(reason) {
481-
throw new ErlangTypes.Tuple(reason, []);
481+
if (reason instanceof Map && reason.has(Symbol.for('__exception__'))) {
482+
let name = Symbol.keyFor(reason.get(Symbol.for('__struct__')).__MODULE__);
483+
name = name
484+
.split('.')
485+
.slice(1)
486+
.join('.');
487+
const message = reason.get(Symbol.for('message'));
488+
throw new Error(`** (${name}) ${message}`);
489+
} else if (is_binary(reason)) {
490+
throw new Error(`** (RuntimeError) ${reason}`);
491+
} else {
492+
throw new Error(`** (ErlangError) Erlang Error ${reason.toString()}`);
493+
}
482494
}
483495

484496
function exit(...args) {

src/javascript/tests/core/erlang_compat/erlang_spec.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,34 @@ test('equals', (t) => {
132132
t.is(Core.erlang.equals(ref, ref), true);
133133
t.is(Core.erlang.equals(ref, new Core.Reference()), false);
134134
});
135+
136+
test('error/1', (t) => {
137+
let error = t.throws(() => {
138+
Core.erlang.error(
139+
new Map([
140+
[Symbol.for('__exception__'), true],
141+
[Symbol.for('message'), 'hi'],
142+
[
143+
Symbol.for('__struct__'),
144+
{
145+
__MODULE__: Symbol.for('Elixir.ArgumentError'),
146+
},
147+
],
148+
]),
149+
);
150+
}, Error);
151+
152+
t.is(error.message, '** (ArgumentError) hi');
153+
154+
error = t.throws(() => {
155+
Core.erlang.error('hi');
156+
}, Error);
157+
158+
t.is(error.message, '** (RuntimeError) hi');
159+
160+
error = t.throws(() => {
161+
Core.erlang.error(new Core.Tuple('abc', 's'));
162+
}, Error);
163+
164+
t.is(error.message, '** (ErlangError) Erlang Error {abc, s}');
165+
});

test/support/integration.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ defmodule Integration do
77

88
def shorthand_failure do
99
orders = [%{email: "[email protected]"},%{email: "[email protected]"}]
10-
options = Enum.reduce(orders, [],
10+
Enum.reduce(orders, [],
1111
&(&2 ++ [ [:option, %{value: &1.email}, &1.email] ]))
1212
end
1313

0 commit comments

Comments
 (0)