Skip to content

Commit 949f30d

Browse files
fix: Fix/1537 improve domain error message (#2545)
* fix: improve error reporting for duplicate use of Ash.Domain
1 parent aefd975 commit 949f30d

File tree

3 files changed

+21
-17
lines changed

3 files changed

+21
-17
lines changed

lib/ash/domain/domain.ex

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,23 @@ defmodule Ash.Domain do
5151
@impl Spark.Dsl
5252
def handle_opts(opts) do
5353
quote do
54+
if Module.get_attribute(__MODULE__, :__ash_domain_used__) do
55+
first_line = Module.get_attribute(__MODULE__, :__ash_domain_used__)
56+
57+
raise CompileError,
58+
file: __ENV__.file,
59+
line: __ENV__.line,
60+
description: """
61+
`use Ash.Domain` can only be called once per module.
62+
63+
It was already called on line #{first_line}.
64+
Remove the duplicate `use Ash.Domain` invocation.
65+
"""
66+
end
67+
68+
# Mark that `use Ash.Domain` has been called and store the line number
69+
@__ash_domain_used__ __ENV__.line
70+
5471
@behaviour Ash.Domain
5572

5673
@impl Ash.Domain

lib/ash/domain/interface.ex

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,6 @@ defmodule Ash.Domain.Interface do
66
@moduledoc false
77

88
defmacro __using__(_) do
9-
env = __CALLER__
10-
11-
ash_domain_already_using =
12-
Module.get_attribute(env.module, :__ash_domain_used__) || false
13-
14-
if ash_domain_already_using do
15-
raise CompileError,
16-
file: env.file,
17-
line: env.line,
18-
description: "use Ash.Domain can be called only one time in module "
19-
end
20-
21-
Module.register_attribute(env.module, :__ash_domain_used__, [])
22-
Module.put_attribute(env.module, :__ash_domain_used__, env.line)
23-
249
quote bind_quoted: [], generated: true do
2510
@spec can?(
2611
query_or_changeset_or_action ::

test/domain/domain_test.exs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,11 @@ defmodule Ash.Test.Resource.DomainTest do
4040
flunk("expected CompileError on the second `use Ash.Domain`")
4141
rescue
4242
e in CompileError ->
43-
assert e.line == 1
43+
# Error should point to line 3 (the second `use Ash.Domain` invocation)
44+
assert e.line == 3
4445
assert String.contains?(e.description, "use Ash.Domain")
45-
assert String.contains?(e.description, "only one")
46+
assert String.contains?(e.description, "can only be called once")
47+
assert String.contains?(e.description, "Remove the duplicate")
4648
end
4749
end
4850

0 commit comments

Comments
 (0)