首页 > 解决方案 > Marshmallow serialization - a way to catch exceptions on a per field basis?

问题描述

Is there a way to catch exceptions (that occur when accessing a property) on a per-field basis with marshmallow [1] ?

I want to use marshmallow to serialize documents of a mongo db (mongoengine) database. With nested schemas, referenced objects are serialized as well.

However, in case of a reference that does not exist, mongoengine throws an error. I would like to catch that error in the process of serialization ( e.g and set field null)

[1] library for converting complex datatypes, such as objects, to and from native Python datatypes https://marshmallow.readthedocs.io/en/3.0/api_reference.html

标签: pythonmongodbmongoenginemarshmallow

解决方案


I ended up subclassing the Nested field and overriding the get_value method.

from marshmallow import Schema, fields
from mongoengine.errors import DoesNotExist


class SafeNested(fields.Nested):
    def get_value(self, *args, **kwargs):
        try:
            return super().get_value(*args, **kwargs)
        except DoesNotExist:
            return {}

推荐阅读