错误

JSONAPI 1.0规范推荐的返回错误形式如下:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/vnd.api+json

{
  "errors": [
    {
      "status": "422",
      "source": {
        "pointer":"/data/attributes/first-name"
      },
      "title":  "Invalid Attribute",
      "detail": "First name must contain at least three characters."
    }
  ],
  "jsonapi": {
    "version": "1.0"
  }
}

其中,“source”字段给出的是,输入数据或查询字段的错误信息。

上例,演示了出现输入数据的错误信息。下例,演示的是查询字段“include”的错误信息:

HTTP/1.1 400 Bad Request
Content-Type: application/vnd.api+json

{
  "errors": [
    {
      "status": "400",
      "source": {
        "parameter": "include"
      },
      "title":  "BadRequest",
      "detail": "Include parameter is invalid"
    }
  ],
  "jsonapi": {
    "version": "1.0"
  }
}

Flask-REST-JSONAPI 提供了两类错误处理的模块:

  • the errors module:我们能从jsonapi_errors模块导入errors module。通过这个错误处理的包,我们能创建一系列,符合JSONAPI 1.0规范,结构化的错误返回结果。
  • the exception module:我们能从这个模块中导入许多异常,同样,我们也能创建一系列,符合JSONAPI 1.0规范,结构化的异常返回结果。

当我们定制api时,强烈建议使用Flask-REST-JSONAPI的exception模块。因为JsonApiException会被框架捕获,并输出符合JSONAPI 1.0规范的内容。

例:

# all required imports are not displayed in this example
from flask_rest_jsonapi.exceptions import ObjectNotFound

class ComputerList(ResourceList):
    def query(self, view_kwargs):
        query_ = self.session.query(Computer)
        if view_kwargs.get('id') is not None:
            try:
                self.session.query(Person).filter_by(id=view_kwargs['id']).one()
            except NoResultFound:
                raise ObjectNotFound({'parameter': 'id'}, "Person: {} not found".format(view_kwargs['id']))
            else:
                query_ = query_.join(Person).filter(Person.id == view_kwargs['id'])
        return query_