marshmallow ValidationError not handled correctly by flask error handler


I don’t know if this matters, but I’m actually using flask-restplus extension.

All of my other flask error handlers work as expected, but for some reason when handling a marshmallow ValidationError, the response is just my original request body, instead of the marshmallow error message. I’ve done some debugging and I know that the error handler is being called, and that attributes of the ValidationError are accessible (e.g. verified that error.messages is {'age': ['Missing data for required field.']}).

Has anyone experienced this before? Thanks for reading, and thanks in advance for any help!

The payload:

{"name": "Bob"}

The error handler:

from marshmallow.exceptions import ValidationError

def marshmallow_error_handler(error):
    # print(error.messages) results in expected {'age': ['Missing data for required field.']}
    return error.messages, 400

The schema:

class SimpleSchema(Schema):
    name = fields.String(required=True)
    age = fields.String(required=True)

Simple route to test handler:

class MarshmallowTest(Resource):
    def post(self):

Expected response:

{'age': ['Missing data for required field.']}

Actual response:

{"name": "Bob"}

I’ve been able to work around this by overriding marshmallow.Schema‘s handle_error function and raising a custom exception, but I’m still quite curious what’s causing this behavior!


I ran into this error as well and found this Github issue

The workaround I went with is overwriting the data property of the exception in my own handler

    def handle_unexpected_within_restx(e):
        data = compose_error_response(e.messages)
        # = data
        return data, 400

Answered By – ken4z

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published