python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.16k stars 335 forks source link

Allow Error Handler to Return HttpResponse #458

Open JavaScriptDude opened 2 years ago

JavaScriptDude commented 2 years ago

I would like to have full control of the response from error handlers assigned using @api.errorhandler decorator so I can obfuscate the return of calls for some usecases.

For example:

@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    log.error("<error_dump>", error)
    response = flask.make_response()
    response.set_data(":(")
    response.status_code = 418
    response.headers['Content-Type'] = 'text/html'
    response.headers['Server'] = 'Timex Sinclair'
    return response

However, the code assumes full control of the response assuming that a dict is returned.

The change is quite simple. In Api.py after result = handler(e):

if not result is None and  issubclass(result.__class__, BaseResponse):
    return result
JavaScriptDude commented 2 years ago

Created PR https://github.com/python-restx/flask-restx/pull/459

JavaScriptDude commented 2 years ago

The only way to do this is at present is by doing the following which is not ideal at all and it does not allow overriding of Content-Type.

app = Flask()
app.config['ERROR_INCLUDE_MESSAGE'] = False
# ...
@app.errorhandler(werkzeug.exceptions.BadRequest)
def handle_bad_request(e):
    log.error("<error_dump>", error)
    return (":(", 418, Headers({'Server': 'Timex Sinclair'}))