'How to fix Marshmallow ValidationError while integrating with marshmallow in case of invalid parameters?

I'm using marshmallow to perform serialization, deserialization along with flaskapispec to produce the swagger api docs.

Schema

class FooSchema(ma.Schema):
    username = ma.fields.Str(required=True)
    password = ma.fields.Str(required=True)
    approved = ma.fields.Date(required=True)

    @ma.validates("username")
    def validate_username(self, value):
        if value != "test":
            raise ma.ValidationError("Improper username")

    @ma.validates("approved")
    def validate_approved(self, value):
        """Validate such that the approved date must be +1 day from today"""
        x = (value - datetime.date.today()).total_seconds()
        print(x)
        if x <= 0:
            raise ma.ValidationError("Error validating date")

View

from flask_apispec import use_kwargs, marshal_with
from flask import Flask, request, jsonify

@app.route('/foo')
@use_kwargs(FooSchema(many=False))
@marshal_with(ResponseSchame, 200)
def foo_view():
    try:
        serializer = FooSchema()
        serializer.load(json.loads(request.data))
    except ValidationError as vae:
        return jsonify(
            {
                "status": "error",
                "message": vae.messages
            }
        )
        
    return {"asd": "Asd"}, 200

Issue here is, exception generated ValidationError from schema is not being caught by the view function, if i remove the apispec decorators it works fine and gets caught by the view.

I've tried:

  • Raising custom exception from schema and catching on view, exception handler.
  • Tried catching all exception generated using @app.errorhandler


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source