Skip to content
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
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
19 changes: 19 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,25 @@ def test_range_fail(type, value, expect):
assert expect in exc_info.value.message


@pytest.mark.parametrize(
("error_message", "expected"),
[
("bad value: nope", "bad value: nope"),
("", "nope"),
],
)
def test_func_param_type_uses_value_error_message(error_message, expected):
def parse(value):
raise ValueError(error_message if error_message else "")

func_type = click.types.FuncParamType(parse)

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

assert expected 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
Loading