Skip to content

error handler type check fails #4295

@delicb

Description

@delicb

In my project, I had the same situation as described in #4095 and my workaround was the same (casting exception to appropriate type). Reading release notes for Flask 2.0.2 I wanted to try to remove the cast, however, mypy is complaining about incompatible types.

The example I am using is:

    # other stuff omitted for brevity, e.g. log initialization, import jsonify, etc
    from flask.typing import ResponseReturnValue

    @app.errorhandler(Exception)
    def handle_any_exception(e: Exception) -> ResponseReturnValue:
        """
        Base exception handler, just log an exception and return 500
        """
        log.exception("unexpected error")
        return jsonify({
            "message": str(e)
        }), 500

Error mypy is reporting:

xxx/__init__.py: note: In function "register_error_handlers":
xxx/__init__.py:115: error: Argument 1 has incompatible type
"Callable[[Exception], Union[Union[Response, Any, Dict[str, Any], Generator[Any, None, None]], Tuple[Union[Response, Any, Dict[str, Any], Generator[Any, None, None]], Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, Any, Dict[str, Any], Generator[Any, None, None]], int], Tuple[Union[Response, Any, Dict[str, Any], Generator[Any, None, None]], int, Union[Headers, Dict[str, Union[str, List[str], Tuple[str, ...]]], List[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Callable[[Dict[str, Any], StartResponse], Iterable[bytes]]]]";
expected "ErrorHandlerCallable[Exception]"  [arg-type]
        @app.errorhandler(Exception)
         ^
Found 1 error in 1 file (checked 8 source files)

Using app.register_error_handler gives the same result.

With 2.0.2 release, cast is not a workaround any more, since it fails before that.

Of course, I did not need cast here earlier, since I am handling the base exception, but the same behavior exists when I am trying to handle werkzeug.exceptions.HTTPException.

I expected mypy type check to pass with provided code.

Environment:

  • Python version: 3.10.0 and 3.9.7
  • Flask version: 2.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions