Skip to content

Commit 2a6039d

Browse files
author
José Valim
committed
Improve error messages for bad arity errors
1 parent 33035e9 commit 2a6039d

File tree

4 files changed

+12
-5
lines changed

4 files changed

+12
-5
lines changed

lib/elixir/lib/exception.ex

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,16 @@ end
5454

5555
defexception BadArityError, [function: nil, args: nil] do
5656
def message(exception) do
57-
args = Enum.map_join(exception.args, ", ", &inspect/1)
58-
"bad arity error: #{inspect(exception.function)} called with (#{args})"
57+
fun = exception.function
58+
args = exception.args
59+
insp = Enum.map_join(args, ", ", &inspect/1)
60+
{ :arity, arity } = :erlang.fun_info(fun, :arity)
61+
"#{inspect(fun)} with arity #{arity} called with #{count(length(args), insp)}"
5962
end
63+
64+
defp count(0, _insp), do: "no arguments"
65+
defp count(1, insp), do: "1 argument (#{insp})"
66+
defp count(x, insp), do: "#{x} arguments (#{insp})"
6067
end
6168

6269
defexception UndefinedFunctionError, [module: nil, function: nil, arity: nil] do

lib/elixir/lib/inspect.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -481,7 +481,7 @@ defimpl Inspect, for: Function do
481481
end
482482

483483
defp default_inspect(mod, fun_info) do
484-
"#Function<#{uniq(fun_info)} in #{Inspect.Atom.inspect(mod)}.#{extract_name(fun_info[:name])}>"
484+
"#Function<#{uniq(fun_info)}/#{fun_info[:arity]} in #{Inspect.Atom.inspect(mod)}.#{extract_name(fun_info[:name])}>"
485485
end
486486

487487
defp extract_name(name) do

lib/elixir/test/elixir/exception_test.exs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ defmodule Kernel.ExceptionTest do
6262

6363
test "format_fa" do
6464
assert Exception.format_fa(fn -> end, 1) =~
65-
%r"#Function<\d\.\d+ in Kernel\.ExceptionTest\.test format_fa/1>/1"
65+
%r"#Function<\d\.\d+/0 in Kernel\.ExceptionTest\.test format_fa/1>/1"
6666
end
6767

6868
test "runtime error message" do

lib/elixir/test/elixir/kernel/rescue_test.exs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ defmodule Kernel.RescueTest do
169169

170170
test :badarity_error do
171171
fun = fn(x) -> x end
172-
string = "bad arity error: #{inspect(fun)} called with (1, 2)"
172+
string = "#{inspect(fun)} with arity 1 called with 2 arguments (1, 2)"
173173

174174
result = try do
175175
fun.(1, 2)

0 commit comments

Comments
 (0)