Skip to content

Possible to rewrite BadRequest response contents? #72

@agjendem

Description

@agjendem

Ask a question
Hi!

This might very well be by design or my incorrect usage of the framework, but I expected to be able to use an error handler to rewrite the response generated when a request fails input validation as defined by my @api.expect()-model.

I'm replacing a system, and I'm trying to keep the responses as close to the old systems format as possible.

I can see while debugging that my custom error handler is triggered, but it seems as there is a "data"-field on the BadRequest exception, that my response in the end is disregarded and the original message is returned to the client? (https://github.com/python-restx/flask-restx/blob/master/flask_restx/api.py#L700)

Additional context
Code to reproduce the issue:

from flask import Flask, request
from flask_restx import Resource, Api, fields


app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = False
api = Api(app)


# Actual validation error: werkzeug.exceptions.BadRequest
@api.errorhandler(Exception)
def handle_validation_error(error):
    return {'my custom': 'error message'}, 400


resource_fields = api.model('Resource', {
    'name': fields.String,
})


@api.route('/hello')
class HelloResource(Resource):
    @api.expect(resource_fields, validate=True)
    def post(self):
        json_data = request.get_json()
        return f'Hello {json_data["name"]}', 200


if __name__ == '__main__':
    app.run(debug=True)
  • Invalid request that I hoped should return my custom error message as json:
curl --data '{"name": 42}' -H 'Content-Type: application/json' http://127.0.0.1:5000/hello

Actual response:

{
    "errors": {
        "name": "42 is not of type 'string'"
    },
    "message": "Input payload validation failed"
}

Expected response:

{"my custom": "error message"}
  • Valid request (for reference):
curl --data '{"name": "Anders"}' -H 'Content-Type: application/json' http://127.0.0.1:5000/hello

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions