Skip to content
Open
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
2 changes: 2 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ Unreleased
:issue:`3043`
- Add :class:`NoSuchCommand` exception with suggestions for misspelled
commands. :issue:`3107` :pr:`3228`
- Use :class:`ValueError` message when conversion in :class:`FuncParamType` would
fail. :issue:`3105` :pr:`3211`
- Add ``click.get_pager_file`` for file-like access to an output
pager. :pr:`1572`

Expand Down
15 changes: 9 additions & 6 deletions src/click/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,13 +195,16 @@ def convert(
) -> ParamTypeValue:
try:
return self.func(value)
except ValueError:
try:
value = str(value)
except UnicodeError:
value = value.decode("utf-8", "replace")
except ValueError as exc:
message = str(exc)

if not message:
try:
message = str(value)
except UnicodeError:
message = value.decode("utf-8", "replace")

self.fail(value, param, ctx)
self.fail(message, param, ctx)


class UnprocessedParamType(ParamType[t.Any]):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ def test_range_fail(type, value, expect):
assert expect in exc_info.value.message


def test_func_param_type_uses_value_error_message():
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@StevOti can you @parametrize the test you added here to test the empty message fallback?

def parse(value):
raise ValueError(f"bad value: {value}")

func_type = click.types.FuncParamType(parse)

with pytest.raises(click.BadParameter) as exc_info:
func_type.convert("nope", None, None)

assert "bad value: nope" in exc_info.value.message


def test_float_range_no_clamp_open():
with pytest.raises(TypeError):
click.FloatRange(0, 1, max_open=True, clamp=True)
Expand Down