flask-smorest icon indicating copy to clipboard operation
flask-smorest copied to clipboard

Improved abort method

Open der-joel opened this issue 3 years ago • 1 comments

Currently flask-smorest republishes the abort-method of Flask-Restful, which accepts additional keyword-args and an exception. However, in ErrorHandlerMixin.handle_http_exception only message, errors and headers are supported as keyword-args. Everything else is ignored, which is quite confusing behaviour.

A flask-smorest specific abort like this would avoid confusion and allow proper type hints:

def abort(http_status_code: int,
          message: typing.Optional[str] = None,
          errors: typing.Optional[typing.Mapping] = None,
          headers: typing.Optional[typing.Mapping] = None):
    """
    Raise an HTTPException for the given http_status_code.
    :param http_status_code: the HTTP status code
    :param message: an error message
    :param errors: can be passed to define the location(s) of the error(s)
    :param headers: additional headers to be passed to the response
    """
    try:
        flask.abort(http_status_code)
    except HTTPException as err:
        # re-raise exception with additional information
        data = {}
        if message is not None:
            data["message"] = message
        if errors is not None:
            data["errors"] = errors
        if headers is not None:
            data["headers"] = headers
        err.data = data
        raise err

der-joel avatar Dec 26 '21 14:12 der-joel

This is documented in handle_http_exception. But indeed the doc for abort is not helpful at all. So this is at least a doc issue.

I'd rather keep the code as is. The point is the user may pass any keywords and override handle_http_exception for custom handling.

lafrech avatar Jan 05 '22 15:01 lafrech