# 错误 JSONAPI 1.0规范推荐的返回错误形式如下: ``` http 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 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](https://github.com/miLibris/flask-rest-jsonapi/blob/master/flask_rest_jsonapi/errors.py)。通过这个错误处理的包,我们能创建一系列,符合JSONAPI 1.0规范,结构化的错误返回结果。 - **the exception module**:我们能从这个[模块](https://github.com/miLibris/flask-rest-jsonapi/blob/master/flask_rest_jsonapi/exceptions.py)中导入许多异常,同样,我们也能创建一系列,符合JSONAPI 1.0规范,结构化的异常返回结果。 当我们定制api时,强烈建议使用Flask-REST-JSONAPI的exception模块。因为JsonApiException会被框架捕获,并输出符合JSONAPI 1.0规范的内容。 例: ``` python # 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_ ```