Skip to content
Myr

refactor error checks in register_error_handler

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Qingpeng Li · committed by David Lord · parent f976d5b · Browse files · 4 files+42 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: David Lord <davidism@gmail.com>

Diff stats

4 files+42 added−37 removed

  • tests:+16 added−17 removed
  • other:+26 added−20 removed

4 files+42 added−37 removed

modified:src/flask/scaffold.py+23 added-20 removed
695 unmodified lines
696 usage.697698 .. versionadded:: 0.7699 """700 if isinstance(code_or_exception, HTTPException): # old broken behavior701 raise ValueError(702 "Tried to register a handler for an exception instance"703 f" {code_or_exception!r}. Handlers can only be"704 " registered for exception classes or HTTP error codes."705 )706707 try:708 exc_class, code = self._get_exc_class_and_code(code_or_exception)700 exc_class, code = self._get_exc_class_and_code(code_or_exception)709 except KeyError:710 raise KeyError(711 f"'{code_or_exception}' is not a recognized HTTP error"712 " code. Use a subclass of HTTPException with that code"713 " instead."714 ) from None715701 self.error_handler_spec[None][code][exc_class] = f702703 @staticmethod704 def _get_exc_class_and_code(
6 unmodified lines
711 :param exc_class_or_code: Any exception class, or an HTTP status712 code as an integer.713 """714 exc_class: t.Type[Exception]715716 if isinstance(exc_class_or_code, int):717 try:731 exc_class = default_exceptions[exc_class_or_code]718 exc_class = default_exceptions[exc_class_or_code]719 except KeyError:720 raise ValueError(721 f"'{exc_class_or_code}' is not a recognized HTTP"722 " error code. Use a subclass of HTTPException with"723 " that code instead."724 ) from None725 else:726 exc_class = exc_class_or_code727735 assert issubclass(736 exc_class, Exception737 ), "Custom exceptions must be subclasses of Exception."728 if isinstance(exc_class, Exception):729 raise TypeError(730 f"{exc_class!r} is an instance, not a class. Handlers"731 " can only be registered for Exception classes or HTTP"732 " error codes."733 )734735 if not issubclass(exc_class, Exception):736 raise ValueError(737 f"'{exc_class.__name__}' is not a subclass of Exception."738 " Handlers can only be registered for Exception classes"739 " or HTTP error codes."740 )741742 if issubclass(exc_class, HTTPException):743 return exc_class, exc_class.code744 else:745 return exc_class, None
127 unmodified lines
modified:tests/test_basic.py-7 removed
897 unmodified lines
898 assert rv.status_code == 403899 assert b"forbidden" == rv.data900901902def test_error_handler_unknown_code(app):903 with pytest.raises(KeyError) as exc_info:904 app.register_error_handler(999, lambda e: ("999", 999))905906 assert "Use a subclass" in exc_info.value.args[0]907908902def test_error_handling_processing(app, client):903 app.testing = False904905 @app.errorhandler(500)
1124 unmodified lines
modified:tests/test_user_error_handler.py+16 added-10 removed
9 unmodified lines
10def test_error_handler_no_match(app, client):11 class CustomException(Exception):12 pass1314 class UnacceptableCustomException(BaseException):15 pass1614 @app.errorhandler(CustomException)15 def custom_exception_handler(e):16 assert isinstance(e, CustomException)17 return "custom"1822 with pytest.raises(23 AssertionError, match="Custom exceptions must be subclasses of Exception."24 ):25 app.register_error_handler(UnacceptableCustomException, None)19 with pytest.raises(TypeError) as exc_info:20 app.register_error_handler(CustomException(), None)2122 assert "CustomException() is an instance, not a class." in str(exc_info.value)2324 with pytest.raises(ValueError) as exc_info:25 app.register_error_handler(list, None)2627 assert "'list' is not a subclass of Exception." in str(exc_info.value)2829 @app.errorhandler(500)30 def handle_500(e):31 assert isinstance(e, InternalServerError)30 original = getattr(e, "original_exception", None)3232 if original is not None:33 return f"wrapped {type(original).__name__}"33 if e.original_exception is not None:34 return f"wrapped {type(e.original_exception).__name__}"3536 return "direct"3738 with pytest.raises(ValueError) as exc_info:39 app.register_error_handler(999, None)4041 assert "Use a subclass of HTTPException" in str(exc_info.value)4243 @app.route("/custom")44 def custom_test():45 raise CustomException()46
249 unmodified lines
modified:CHANGES.rst+3 added
3 unmodified lines
4-------------56Unreleased78- Refactor ``register_error_handler`` to consolidate error checking.9 Rewrite some error messages to be more consistent. :issue:`4559`101112Version 2.1.213-------------1415Released 2022-04-28
1278 unmodified lines