We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Crash with "in <string>' requires string as left operand, not int"
```
ValidationError: 'minVersion' is a required property

Failed validating 'required' in schema['properties']['versionRange']['items']['properties']['targetApplication']['items']:
    {'additionalProperties': False,
     'description': 'Target application',
     'properties': {'guid': {'description': 'The application unique '
                                            'identifier.',
                             'enum': ['{ec8030f7-c20a-464f-9b0e-13a3a9e97384}',
                                      '{3550f703-e582-4d05-9a08-453d09bdfdc6}',
                                      '{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}',
                                      '{aa3c5121-dab2-40e2-81ca-7ea25febc110}'],
                             'enumNames': ['Firefox',
                                           'Thunderbird',
                                           'Seamonkey',
                                           'Android'],
                             'title': 'Application id',
                             'type': 'string'},
                    'maxVersion': {'$ref': '#/definitions/maxVersion'},
                    'minVersion': {'$ref': '#/definitions/minVersion'}},
     'required': ['guid', 'minVersion', 'maxVersion'],
     'title': 'Target application',
     'type': 'object'}

On instance['versionRange'][0]['targetApplication'][0]:
    {'guid': 'ec8030f7-c20a-464f-9b0e-13a3a9e97384', 'maxVersion': '57.0.*'}
  File "kinto/views/records.py", line 73, in process_record
    jsonschema.validate(data, schema)
  File "jsonschema/validators.py", line 541, in validate
    cls(schema, *args, **kwargs).validate(instance)
  File "jsonschema/validators.py", line 130, in validate
    raise error

TypeError: 'in <string>' requires string as left operand, not int
(11 additional frame(s) were not displayed)
...
  File "cornice/service.py", line 494, in wrapper
    response = view_()
  File "kinto/core/resource/__init__.py", line 463, in put
    new_record = self.process_record(post_record, old=existing)
  File "kinto/views/records.py", line 81, in process_record
    raise_invalid(self.request, name=field, description=e.message)
  File "kinto/core/errors.py", line 178, in raise_invalid
    response = json_error_handler(request)
  File "kinto/core/errors.py", line 149, in json_error_handler
    if name in description:
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `kinto/core/errors.py`
Content:
```
1 import colander
2 import logging
3 from pyramid import httpexceptions
4 from enum import Enum
5 
6 from kinto.core.schema import Any
7 from kinto.core.utils import json, reapply_cors
8 
9 
10 class ERRORS(Enum):
11     """Predefined errors as specified by the API.
12 
13     +-------------+-------+------------------------------------------------+
14     | Status code | Errno | Description                                    |
15     +=============+=======+================================================+
16     | 401         | 104   | Missing Authorization Token                    |
17     +-------------+-------+------------------------------------------------+
18     | 401         | 105   | Invalid Authorization Token                    |
19     +-------------+-------+------------------------------------------------+
20     | 400         | 106   | request body was not valid JSON                |
21     +-------------+-------+------------------------------------------------+
22     | 400         | 107   | invalid request parameter                      |
23     +-------------+-------+------------------------------------------------+
24     | 400         | 108   | missing request parameter                      |
25     +-------------+-------+------------------------------------------------+
26     | 400         | 109   | invalid posted data                            |
27     +-------------+-------+------------------------------------------------+
28     | 404         | 110   | Invalid Token / id                             |
29     +-------------+-------+------------------------------------------------+
30     | 404         | 111   | Missing Token / id                             |
31     +-------------+-------+------------------------------------------------+
32     | 411         | 112   | Content-Length header was not provided         |
33     +-------------+-------+------------------------------------------------+
34     | 413         | 113   | Request body too large                         |
35     +-------------+-------+------------------------------------------------+
36     | 412         | 114   | Resource was modified meanwhile                |
37     +-------------+-------+------------------------------------------------+
38     | 405         | 115   | Method not allowed on this end point           |
39     +-------------+-------+------------------------------------------------+
40     | 404         | 116   | Requested version not available on this server |
41     +-------------+-------+------------------------------------------------+
42     | 429         | 117   | Client has sent too many requests              |
43     +-------------+-------+------------------------------------------------+
44     | 403         | 121   | Resource's access forbidden for this user      |
45     +-------------+-------+------------------------------------------------+
46     | 409         | 122   | Another resource violates constraint           |
47     +-------------+-------+------------------------------------------------+
48     | 500         | 999   | Internal Server Error                          |
49     +-------------+-------+------------------------------------------------+
50     | 503         | 201   | Service Temporary unavailable due to high load |
51     +-------------+-------+------------------------------------------------+
52     | 410         | 202   | Service deprecated                             |
53     +-------------+-------+------------------------------------------------+
54     """
55 
56     MISSING_AUTH_TOKEN = 104
57     INVALID_AUTH_TOKEN = 105
58     BADJSON = 106
59     INVALID_PARAMETERS = 107
60     MISSING_PARAMETERS = 108
61     INVALID_POSTED_DATA = 109
62     INVALID_RESOURCE_ID = 110
63     MISSING_RESOURCE = 111
64     MISSING_CONTENT_LENGTH = 112
65     REQUEST_TOO_LARGE = 113
66     MODIFIED_MEANWHILE = 114
67     METHOD_NOT_ALLOWED = 115
68     VERSION_NOT_AVAILABLE = 116
69     CLIENT_REACHED_CAPACITY = 117
70     FORBIDDEN = 121
71     CONSTRAINT_VIOLATED = 122
72     UNDEFINED = 999
73     BACKEND = 201
74     SERVICE_DEPRECATED = 202
75 
76 
77 class ErrorSchema(colander.MappingSchema):
78     """Payload schema for Kinto errors."""
79 
80     code = colander.SchemaNode(colander.Integer())
81     errno = colander.SchemaNode(colander.Integer())
82     error = colander.SchemaNode(colander.String())
83     message = colander.SchemaNode(colander.String(), missing=colander.drop)
84     info = colander.SchemaNode(colander.String(), missing=colander.drop)
85     details = colander.SchemaNode(Any(), missing=colander.drop)
86 
87 
88 def http_error(
89     httpexception, errno=None, code=None, error=None, message=None, info=None, details=None
90 ):
91     """Return a JSON formated response matching the error HTTP API.
92 
93     :param httpexception: Instance of :mod:`~pyramid:pyramid.httpexceptions`
94     :param errno: stable application-level error number (e.g. 109)
95     :param code: matches the HTTP status code (e.g 400)
96     :param error: string description of error type (e.g. "Bad request")
97     :param message: context information (e.g. "Invalid request parameters")
98     :param info: information about error (e.g. URL to troubleshooting)
99     :param details: additional structured details (conflicting object)
100     :returns: the formatted response object
101     :rtype: pyramid.httpexceptions.HTTPException
102     """
103     errno = errno or ERRORS.UNDEFINED
104 
105     if isinstance(errno, Enum):
106         errno = errno.value
107 
108     body = {
109         "code": code or httpexception.code,
110         "errno": errno,
111         "error": error or httpexception.title,
112         "message": message,
113         "info": info,
114         "details": details or colander.drop,
115     }
116 
117     response = httpexception
118     response.errno = errno
119     response.json = ErrorSchema().deserialize(body)
120     response.content_type = "application/json"
121     return response
122 
123 
124 def json_error_handler(request):
125     """Cornice JSON error handler, returning consistant JSON formatted errors
126     from schema validation errors.
127 
128     This is meant to be used is custom services in your applications.
129 
130     .. code-block:: python
131 
132         upload = Service(name="upload", path='/upload',
133                          error_handler=errors.json_error_handler)
134 
135     .. warning::
136 
137         Only the first error of the list is formatted in the response.
138         (c.f. HTTP API).
139     """
140     errors = request.errors
141     sorted_errors = sorted(errors, key=lambda x: str(x["name"]))
142     # In Cornice, we call error handler if at least one error was set.
143     error = sorted_errors[0]
144     name = error["name"]
145     description = error["description"]
146 
147     if isinstance(description, bytes):
148         description = error["description"].decode("utf-8")
149 
150     if name is not None:
151         if name in description:
152             message = description
153         else:
154             message = "{name} in {location}: {description}".format_map(error)
155     else:
156         message = "{location}: {description}".format_map(error)
157 
158     response = http_error(
159         httpexceptions.HTTPBadRequest(),
160         code=errors.status,
161         errno=ERRORS.INVALID_PARAMETERS.value,
162         error="Invalid parameters",
163         message=message,
164         details=errors,
165     )
166     response.status = errors.status
167     response = reapply_cors(request, response)
168     return response
169 
170 
171 def raise_invalid(request, location="body", name=None, description=None, **kwargs):
172     """Helper to raise a validation error.
173 
174     :param location: location in request (e.g. ``'querystring'``)
175     :param name: field name
176     :param description: detailed description of validation error
177 
178     :raises: :class:`~pyramid:pyramid.httpexceptions.HTTPBadRequest`
179     """
180     request.errors.add(location, name, description, **kwargs)
181     response = json_error_handler(request)
182     raise response
183 
184 
185 def send_alert(request, message=None, url=None, code="soft-eol"):
186     """Helper to add an Alert header to the response.
187 
188     :param code: The type of error 'soft-eol', 'hard-eol'
189     :param message: The description message.
190     :param url: The URL for more information, default to the documentation url.
191     """
192     if url is None:
193         url = request.registry.settings["project_docs"]
194 
195     request.response.headers["Alert"] = json.dumps({"code": code, "message": message, "url": url})
196 
197 
198 def request_GET(request):
199     """Catches a UnicodeDecode error in request.GET in case a wrong request was received.
200     Fixing a webob long term issue: https://github.com/Pylons/webob/issues/161
201     """
202     try:
203         return request.GET
204     except UnicodeDecodeError:
205         querystring = request.environ.get("QUERY_STRING", "")
206         logger = logging.getLogger(__name__)
207         logger.warning("Error decoding QUERY_STRING: %s" % request.environ)
208         raise http_error(
209             httpexceptions.HTTPBadRequest(),
210             errno=ERRORS.INVALID_PARAMETERS,
211             message="A request with an incorrect encoding in the querystring was"
212             "received. Please make sure your requests are encoded in UTF-8: %s" % querystring,
213         )
214
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/kinto/core/errors.py b/kinto/core/errors.py
--- a/kinto/core/errors.py
+++ b/kinto/core/errors.py
@@ -148,7 +148,7 @@
         description = error["description"].decode("utf-8")
 
     if name is not None:
-        if name in description:
+        if str(name) in description:
             message = description
         else:
             message = "{name} in {location}: {description}".format_map(error)

{"golden_diff": "diff --git a/kinto/core/errors.py b/kinto/core/errors.py\n--- a/kinto/core/errors.py\n+++ b/kinto/core/errors.py\n@@ -148,7 +148,7 @@\n         description = error[\"description\"].decode(\"utf-8\")\n \n     if name is not None:\n-        if name in description:\n+        if str(name) in description:\n             message = description\n         else:\n             message = \"{name} in {location}: {description}\".format_map(error)\n", "issue": "Crash with \"in <string>' requires string as left operand, not int\"\n```\r\nValidationError: 'minVersion' is a required property\r\n\r\nFailed validating 'required' in schema['properties']['versionRange']['items']['properties']['targetApplication']['items']:\r\n    {'additionalProperties': False,\r\n     'description': 'Target application',\r\n     'properties': {'guid': {'description': 'The application unique '\r\n                                            'identifier.',\r\n                             'enum': ['{ec8030f7-c20a-464f-9b0e-13a3a9e97384}',\r\n                                      '{3550f703-e582-4d05-9a08-453d09bdfdc6}',\r\n                                      '{92650c4d-4b8e-4d2a-b7eb-24ecf4f6b63a}',\r\n                                      '{aa3c5121-dab2-40e2-81ca-7ea25febc110}'],\r\n                             'enumNames': ['Firefox',\r\n                                           'Thunderbird',\r\n                                           'Seamonkey',\r\n                                           'Android'],\r\n                             'title': 'Application id',\r\n                             'type': 'string'},\r\n                    'maxVersion': {'$ref': '#/definitions/maxVersion'},\r\n                    'minVersion': {'$ref': '#/definitions/minVersion'}},\r\n     'required': ['guid', 'minVersion', 'maxVersion'],\r\n     'title': 'Target application',\r\n     'type': 'object'}\r\n\r\nOn instance['versionRange'][0]['targetApplication'][0]:\r\n    {'guid': 'ec8030f7-c20a-464f-9b0e-13a3a9e97384', 'maxVersion': '57.0.*'}\r\n  File \"kinto/views/records.py\", line 73, in process_record\r\n    jsonschema.validate(data, schema)\r\n  File \"jsonschema/validators.py\", line 541, in validate\r\n    cls(schema, *args, **kwargs).validate(instance)\r\n  File \"jsonschema/validators.py\", line 130, in validate\r\n    raise error\r\n\r\nTypeError: 'in <string>' requires string as left operand, not int\r\n(11 additional frame(s) were not displayed)\r\n...\r\n  File \"cornice/service.py\", line 494, in wrapper\r\n    response = view_()\r\n  File \"kinto/core/resource/__init__.py\", line 463, in put\r\n    new_record = self.process_record(post_record, old=existing)\r\n  File \"kinto/views/records.py\", line 81, in process_record\r\n    raise_invalid(self.request, name=field, description=e.message)\r\n  File \"kinto/core/errors.py\", line 178, in raise_invalid\r\n    response = json_error_handler(request)\r\n  File \"kinto/core/errors.py\", line 149, in json_error_handler\r\n    if name in description:\r\n```\n", "before_files": [{"content": "import colander\nimport logging\nfrom pyramid import httpexceptions\nfrom enum import Enum\n\nfrom kinto.core.schema import Any\nfrom kinto.core.utils import json, reapply_cors\n\n\nclass ERRORS(Enum):\n    \"\"\"Predefined errors as specified by the API.\n\n    +-------------+-------+------------------------------------------------+\n    | Status code | Errno | Description                                    |\n    +=============+=======+================================================+\n    | 401         | 104   | Missing Authorization Token                    |\n    +-------------+-------+------------------------------------------------+\n    | 401         | 105   | Invalid Authorization Token                    |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 106   | request body was not valid JSON                |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 107   | invalid request parameter                      |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 108   | missing request parameter                      |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 109   | invalid posted data                            |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 110   | Invalid Token / id                             |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 111   | Missing Token / id                             |\n    +-------------+-------+------------------------------------------------+\n    | 411         | 112   | Content-Length header was not provided         |\n    +-------------+-------+------------------------------------------------+\n    | 413         | 113   | Request body too large                         |\n    +-------------+-------+------------------------------------------------+\n    | 412         | 114   | Resource was modified meanwhile                |\n    +-------------+-------+------------------------------------------------+\n    | 405         | 115   | Method not allowed on this end point           |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 116   | Requested version not available on this server |\n    +-------------+-------+------------------------------------------------+\n    | 429         | 117   | Client has sent too many requests              |\n    +-------------+-------+------------------------------------------------+\n    | 403         | 121   | Resource's access forbidden for this user      |\n    +-------------+-------+------------------------------------------------+\n    | 409         | 122   | Another resource violates constraint           |\n    +-------------+-------+------------------------------------------------+\n    | 500         | 999   | Internal Server Error                          |\n    +-------------+-------+------------------------------------------------+\n    | 503         | 201   | Service Temporary unavailable due to high load |\n    +-------------+-------+------------------------------------------------+\n    | 410         | 202   | Service deprecated                             |\n    +-------------+-------+------------------------------------------------+\n    \"\"\"\n\n    MISSING_AUTH_TOKEN = 104\n    INVALID_AUTH_TOKEN = 105\n    BADJSON = 106\n    INVALID_PARAMETERS = 107\n    MISSING_PARAMETERS = 108\n    INVALID_POSTED_DATA = 109\n    INVALID_RESOURCE_ID = 110\n    MISSING_RESOURCE = 111\n    MISSING_CONTENT_LENGTH = 112\n    REQUEST_TOO_LARGE = 113\n    MODIFIED_MEANWHILE = 114\n    METHOD_NOT_ALLOWED = 115\n    VERSION_NOT_AVAILABLE = 116\n    CLIENT_REACHED_CAPACITY = 117\n    FORBIDDEN = 121\n    CONSTRAINT_VIOLATED = 122\n    UNDEFINED = 999\n    BACKEND = 201\n    SERVICE_DEPRECATED = 202\n\n\nclass ErrorSchema(colander.MappingSchema):\n    \"\"\"Payload schema for Kinto errors.\"\"\"\n\n    code = colander.SchemaNode(colander.Integer())\n    errno = colander.SchemaNode(colander.Integer())\n    error = colander.SchemaNode(colander.String())\n    message = colander.SchemaNode(colander.String(), missing=colander.drop)\n    info = colander.SchemaNode(colander.String(), missing=colander.drop)\n    details = colander.SchemaNode(Any(), missing=colander.drop)\n\n\ndef http_error(\n    httpexception, errno=None, code=None, error=None, message=None, info=None, details=None\n):\n    \"\"\"Return a JSON formated response matching the error HTTP API.\n\n    :param httpexception: Instance of :mod:`~pyramid:pyramid.httpexceptions`\n    :param errno: stable application-level error number (e.g. 109)\n    :param code: matches the HTTP status code (e.g 400)\n    :param error: string description of error type (e.g. \"Bad request\")\n    :param message: context information (e.g. \"Invalid request parameters\")\n    :param info: information about error (e.g. URL to troubleshooting)\n    :param details: additional structured details (conflicting object)\n    :returns: the formatted response object\n    :rtype: pyramid.httpexceptions.HTTPException\n    \"\"\"\n    errno = errno or ERRORS.UNDEFINED\n\n    if isinstance(errno, Enum):\n        errno = errno.value\n\n    body = {\n        \"code\": code or httpexception.code,\n        \"errno\": errno,\n        \"error\": error or httpexception.title,\n        \"message\": message,\n        \"info\": info,\n        \"details\": details or colander.drop,\n    }\n\n    response = httpexception\n    response.errno = errno\n    response.json = ErrorSchema().deserialize(body)\n    response.content_type = \"application/json\"\n    return response\n\n\ndef json_error_handler(request):\n    \"\"\"Cornice JSON error handler, returning consistant JSON formatted errors\n    from schema validation errors.\n\n    This is meant to be used is custom services in your applications.\n\n    .. code-block:: python\n\n        upload = Service(name=\"upload\", path='/upload',\n                         error_handler=errors.json_error_handler)\n\n    .. warning::\n\n        Only the first error of the list is formatted in the response.\n        (c.f. HTTP API).\n    \"\"\"\n    errors = request.errors\n    sorted_errors = sorted(errors, key=lambda x: str(x[\"name\"]))\n    # In Cornice, we call error handler if at least one error was set.\n    error = sorted_errors[0]\n    name = error[\"name\"]\n    description = error[\"description\"]\n\n    if isinstance(description, bytes):\n        description = error[\"description\"].decode(\"utf-8\")\n\n    if name is not None:\n        if name in description:\n            message = description\n        else:\n            message = \"{name} in {location}: {description}\".format_map(error)\n    else:\n        message = \"{location}: {description}\".format_map(error)\n\n    response = http_error(\n        httpexceptions.HTTPBadRequest(),\n        code=errors.status,\n        errno=ERRORS.INVALID_PARAMETERS.value,\n        error=\"Invalid parameters\",\n        message=message,\n        details=errors,\n    )\n    response.status = errors.status\n    response = reapply_cors(request, response)\n    return response\n\n\ndef raise_invalid(request, location=\"body\", name=None, description=None, **kwargs):\n    \"\"\"Helper to raise a validation error.\n\n    :param location: location in request (e.g. ``'querystring'``)\n    :param name: field name\n    :param description: detailed description of validation error\n\n    :raises: :class:`~pyramid:pyramid.httpexceptions.HTTPBadRequest`\n    \"\"\"\n    request.errors.add(location, name, description, **kwargs)\n    response = json_error_handler(request)\n    raise response\n\n\ndef send_alert(request, message=None, url=None, code=\"soft-eol\"):\n    \"\"\"Helper to add an Alert header to the response.\n\n    :param code: The type of error 'soft-eol', 'hard-eol'\n    :param message: The description message.\n    :param url: The URL for more information, default to the documentation url.\n    \"\"\"\n    if url is None:\n        url = request.registry.settings[\"project_docs\"]\n\n    request.response.headers[\"Alert\"] = json.dumps({\"code\": code, \"message\": message, \"url\": url})\n\n\ndef request_GET(request):\n    \"\"\"Catches a UnicodeDecode error in request.GET in case a wrong request was received.\n    Fixing a webob long term issue: https://github.com/Pylons/webob/issues/161\n    \"\"\"\n    try:\n        return request.GET\n    except UnicodeDecodeError:\n        querystring = request.environ.get(\"QUERY_STRING\", \"\")\n        logger = logging.getLogger(__name__)\n        logger.warning(\"Error decoding QUERY_STRING: %s\" % request.environ)\n        raise http_error(\n            httpexceptions.HTTPBadRequest(),\n            errno=ERRORS.INVALID_PARAMETERS,\n            message=\"A request with an incorrect encoding in the querystring was\"\n            \"received. Please make sure your requests are encoded in UTF-8: %s\" % querystring,\n        )\n", "path": "kinto/core/errors.py"}], "after_files": [{"content": "import colander\nimport logging\nfrom pyramid import httpexceptions\nfrom enum import Enum\n\nfrom kinto.core.schema import Any\nfrom kinto.core.utils import json, reapply_cors\n\n\nclass ERRORS(Enum):\n    \"\"\"Predefined errors as specified by the API.\n\n    +-------------+-------+------------------------------------------------+\n    | Status code | Errno | Description                                    |\n    +=============+=======+================================================+\n    | 401         | 104   | Missing Authorization Token                    |\n    +-------------+-------+------------------------------------------------+\n    | 401         | 105   | Invalid Authorization Token                    |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 106   | request body was not valid JSON                |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 107   | invalid request parameter                      |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 108   | missing request parameter                      |\n    +-------------+-------+------------------------------------------------+\n    | 400         | 109   | invalid posted data                            |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 110   | Invalid Token / id                             |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 111   | Missing Token / id                             |\n    +-------------+-------+------------------------------------------------+\n    | 411         | 112   | Content-Length header was not provided         |\n    +-------------+-------+------------------------------------------------+\n    | 413         | 113   | Request body too large                         |\n    +-------------+-------+------------------------------------------------+\n    | 412         | 114   | Resource was modified meanwhile                |\n    +-------------+-------+------------------------------------------------+\n    | 405         | 115   | Method not allowed on this end point           |\n    +-------------+-------+------------------------------------------------+\n    | 404         | 116   | Requested version not available on this server |\n    +-------------+-------+------------------------------------------------+\n    | 429         | 117   | Client has sent too many requests              |\n    +-------------+-------+------------------------------------------------+\n    | 403         | 121   | Resource's access forbidden for this user      |\n    +-------------+-------+------------------------------------------------+\n    | 409         | 122   | Another resource violates constraint           |\n    +-------------+-------+------------------------------------------------+\n    | 500         | 999   | Internal Server Error                          |\n    +-------------+-------+------------------------------------------------+\n    | 503         | 201   | Service Temporary unavailable due to high load |\n    +-------------+-------+------------------------------------------------+\n    | 410         | 202   | Service deprecated                             |\n    +-------------+-------+------------------------------------------------+\n    \"\"\"\n\n    MISSING_AUTH_TOKEN = 104\n    INVALID_AUTH_TOKEN = 105\n    BADJSON = 106\n    INVALID_PARAMETERS = 107\n    MISSING_PARAMETERS = 108\n    INVALID_POSTED_DATA = 109\n    INVALID_RESOURCE_ID = 110\n    MISSING_RESOURCE = 111\n    MISSING_CONTENT_LENGTH = 112\n    REQUEST_TOO_LARGE = 113\n    MODIFIED_MEANWHILE = 114\n    METHOD_NOT_ALLOWED = 115\n    VERSION_NOT_AVAILABLE = 116\n    CLIENT_REACHED_CAPACITY = 117\n    FORBIDDEN = 121\n    CONSTRAINT_VIOLATED = 122\n    UNDEFINED = 999\n    BACKEND = 201\n    SERVICE_DEPRECATED = 202\n\n\nclass ErrorSchema(colander.MappingSchema):\n    \"\"\"Payload schema for Kinto errors.\"\"\"\n\n    code = colander.SchemaNode(colander.Integer())\n    errno = colander.SchemaNode(colander.Integer())\n    error = colander.SchemaNode(colander.String())\n    message = colander.SchemaNode(colander.String(), missing=colander.drop)\n    info = colander.SchemaNode(colander.String(), missing=colander.drop)\n    details = colander.SchemaNode(Any(), missing=colander.drop)\n\n\ndef http_error(\n    httpexception, errno=None, code=None, error=None, message=None, info=None, details=None\n):\n    \"\"\"Return a JSON formated response matching the error HTTP API.\n\n    :param httpexception: Instance of :mod:`~pyramid:pyramid.httpexceptions`\n    :param errno: stable application-level error number (e.g. 109)\n    :param code: matches the HTTP status code (e.g 400)\n    :param error: string description of error type (e.g. \"Bad request\")\n    :param message: context information (e.g. \"Invalid request parameters\")\n    :param info: information about error (e.g. URL to troubleshooting)\n    :param details: additional structured details (conflicting object)\n    :returns: the formatted response object\n    :rtype: pyramid.httpexceptions.HTTPException\n    \"\"\"\n    errno = errno or ERRORS.UNDEFINED\n\n    if isinstance(errno, Enum):\n        errno = errno.value\n\n    body = {\n        \"code\": code or httpexception.code,\n        \"errno\": errno,\n        \"error\": error or httpexception.title,\n        \"message\": message,\n        \"info\": info,\n        \"details\": details or colander.drop,\n    }\n\n    response = httpexception\n    response.errno = errno\n    response.json = ErrorSchema().deserialize(body)\n    response.content_type = \"application/json\"\n    return response\n\n\ndef json_error_handler(request):\n    \"\"\"Cornice JSON error handler, returning consistant JSON formatted errors\n    from schema validation errors.\n\n    This is meant to be used is custom services in your applications.\n\n    .. code-block:: python\n\n        upload = Service(name=\"upload\", path='/upload',\n                         error_handler=errors.json_error_handler)\n\n    .. warning::\n\n        Only the first error of the list is formatted in the response.\n        (c.f. HTTP API).\n    \"\"\"\n    errors = request.errors\n    sorted_errors = sorted(errors, key=lambda x: str(x[\"name\"]))\n    # In Cornice, we call error handler if at least one error was set.\n    error = sorted_errors[0]\n    name = error[\"name\"]\n    description = error[\"description\"]\n\n    if isinstance(description, bytes):\n        description = error[\"description\"].decode(\"utf-8\")\n\n    if name is not None:\n        if str(name) in description:\n            message = description\n        else:\n            message = \"{name} in {location}: {description}\".format_map(error)\n    else:\n        message = \"{location}: {description}\".format_map(error)\n\n    response = http_error(\n        httpexceptions.HTTPBadRequest(),\n        code=errors.status,\n        errno=ERRORS.INVALID_PARAMETERS.value,\n        error=\"Invalid parameters\",\n        message=message,\n        details=errors,\n    )\n    response.status = errors.status\n    response = reapply_cors(request, response)\n    return response\n\n\ndef raise_invalid(request, location=\"body\", name=None, description=None, **kwargs):\n    \"\"\"Helper to raise a validation error.\n\n    :param location: location in request (e.g. ``'querystring'``)\n    :param name: field name\n    :param description: detailed description of validation error\n\n    :raises: :class:`~pyramid:pyramid.httpexceptions.HTTPBadRequest`\n    \"\"\"\n    request.errors.add(location, name, description, **kwargs)\n    response = json_error_handler(request)\n    raise response\n\n\ndef send_alert(request, message=None, url=None, code=\"soft-eol\"):\n    \"\"\"Helper to add an Alert header to the response.\n\n    :param code: The type of error 'soft-eol', 'hard-eol'\n    :param message: The description message.\n    :param url: The URL for more information, default to the documentation url.\n    \"\"\"\n    if url is None:\n        url = request.registry.settings[\"project_docs\"]\n\n    request.response.headers[\"Alert\"] = json.dumps({\"code\": code, \"message\": message, \"url\": url})\n\n\ndef request_GET(request):\n    \"\"\"Catches a UnicodeDecode error in request.GET in case a wrong request was received.\n    Fixing a webob long term issue: https://github.com/Pylons/webob/issues/161\n    \"\"\"\n    try:\n        return request.GET\n    except UnicodeDecodeError:\n        querystring = request.environ.get(\"QUERY_STRING\", \"\")\n        logger = logging.getLogger(__name__)\n        logger.warning(\"Error decoding QUERY_STRING: %s\" % request.environ)\n        raise http_error(\n            httpexceptions.HTTPBadRequest(),\n            errno=ERRORS.INVALID_PARAMETERS,\n            message=\"A request with an incorrect encoding in the querystring was\"\n            \"received. Please make sure your requests are encoded in UTF-8: %s\" % querystring,\n        )\n", "path": "kinto/core/errors.py"}]}