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
Provenance
- Commit
1e5dd43- Tree
7dcccfc- Author
Qingpeng Li <qingpeng9802@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
f976d5b
4 files changed+42 added−37 removed
modified:src/flask/scaffold.py+23 added-20 removed
695 unmodified lines696 usage.697 698 .. 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- )706-707- 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 None715-701 self.error_handler_spec[None][code][exc_class] = f702 703 @staticmethod704 def _get_exc_class_and_code(6 unmodified lines711 :param exc_class_or_code: Any exception class, or an HTTP status712 code as an integer.713 """714 exc_class: t.Type[Exception]715+716 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_code727 735- 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+ )734 735+ 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+ )741+742 if issubclass(exc_class, HTTPException):743 return exc_class, exc_class.code744 else:745 return exc_class, None127 unmodified linesmodified:tests/test_basic.py-7 removed
897 unmodified lines898 assert rv.status_code == 403899 assert b"forbidden" == rv.data900 901 902-def test_error_handler_unknown_code(app):903- with pytest.raises(KeyError) as exc_info:904- app.register_error_handler(999, lambda e: ("999", 999))905-906- assert "Use a subclass" in exc_info.value.args[0]907-908-902 def test_error_handling_processing(app, client):903 app.testing = False904 905 @app.errorhandler(500)1124 unmodified linesmodified:tests/test_user_error_handler.py+16 added-10 removed
9 unmodified lines10 def test_error_handler_no_match(app, client):11 class CustomException(Exception):12 pass13 14- class UnacceptableCustomException(BaseException):15- pass16-14 @app.errorhandler(CustomException)15 def custom_exception_handler(e):16 assert isinstance(e, CustomException)17 return "custom"18 22- 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)21 22+ assert "CustomException() is an instance, not a class." in str(exc_info.value)23+24+ with pytest.raises(ValueError) as exc_info:25+ app.register_error_handler(list, None)26+27+ assert "'list' is not a subclass of Exception." in str(exc_info.value)28+29 @app.errorhandler(500)30 def handle_500(e):31 assert isinstance(e, InternalServerError)30- original = getattr(e, "original_exception", None)32 32- 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__}"35 36 return "direct"37 38+ with pytest.raises(ValueError) as exc_info:39+ app.register_error_handler(999, None)40+41+ assert "Use a subclass of HTTPException" in str(exc_info.value)42+43 @app.route("/custom")44 def custom_test():45 raise CustomException()46 249 unmodified linesmodified:CHANGES.rst+3 added
3 unmodified lines4 -------------5 6 Unreleased7 8+- Refactor ``register_error_handler`` to consolidate error checking.9+ Rewrite some error messages to be more consistent. :issue:`4559`10 11+12 Version 2.1.213 -------------14 15 Released 2022-04-281278 unmodified lines