jmcarp / flask-apispec

MIT License
655 stars 157 forks source link

No error status code passed to custom error handler on ValidationError #139

Open sanzoghenzo opened 5 years ago

sanzoghenzo commented 5 years ago

Wrapper's call to parser.parse doesn't set error_status_code, so custom error_handlers gets None as status code on ValidationError.

I had to manually add a 400 status code in my error handler. Here's the relevant code:

@parser.error_handler
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
    """webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    status_code = error_status_code or 400
    abort(status_code, errors=err.messages)

class TaskStatusSchema(ma.Schema):
    class Meta:
        strict = True

    task_status = fields.String()

class TaskResource(MethodResource):
    """Base class for Task Resource."""
    methods = ['POST']
    """list: The HTTP methods enabled for this resource. Defaults to POST only."""

    url = ''
    """str: The url for the resource."""

    schema = TaskStatusSchema
    """flask_marshmallow.Schema The Flask Marshmallow schema."""

    args = {}
    """dict[fields]|marshmallow.Schema: dictionary or Schema to pass to webargs."""

    @marshal_with(Ref('schema'), code=202)
    @use_kwargs(Ref('args'))
    def post(self, **kwargs):
        ...
rshah88 commented 5 years ago

Its not even hitting the custom error handler for me and always hitting the generic_error_handler. Any suggestions on that?

sm-moore commented 5 years ago

Seems like this would be a pretty straight forward fix. The webargs function accepts several parameters I feel flask-apispec could support. I'll try and work on a PR for this if it seems worth-while/possible.

daniel-butler commented 4 years ago

Using the code in the original post the error code seems to be adjustable but the error messages don't get passed to the end reponse.

This is the code I am referring too

@parser.error_handler
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
    """webargs error handler that uses Flask-RESTful's abort function to return
    a JSON error response to the client.
    """
    status_code = error_status_code or 400  # if set to 422 the error code will be 422
    abort(status_code, errors=err.messages)

This is what I ended up using https://gist.github.com/hirobert/394981a661cbf78d442e