validation_error.py 1.96 KB
Newer Older
ethiraj krishnamanaidu's avatar
ethiraj krishnamanaidu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2021 Schlumberger
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
16
17
from typing import Union

from fastapi.exceptions import RequestValidationError
fabian serin's avatar
fabian serin committed
18
from fastapi.encoders import jsonable_encoder
19
from fastapi.openapi.constants import REF_PREFIX
fabian serin's avatar
fabian serin committed
20
from fastapi.openapi.utils import validation_error_response_definition, validation_error_definition
21
22
23
24
25
from pydantic import ValidationError
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY

Luc Yriarte's avatar
Luc Yriarte committed
26
27
from app.helper.logger import get_logger

28
29

async def http422_error_handler(
Luc Yriarte's avatar
Luc Yriarte committed
30
    request: Request, exc: Union[RequestValidationError, ValidationError],
31
32
33
34
) -> JSONResponse:
    """
    Catches and handles pydantic validation errors
    """
Luc Yriarte's avatar
Luc Yriarte committed
35
36

    get_logger().exception(f"http422_error_handler - {request.url}")
fabian serin's avatar
fabian serin committed
37
    return JSONResponse(content=jsonable_encoder({"errors": exc.errors()}), status_code=HTTP_422_UNPROCESSABLE_ENTITY)
38
39


fabian serin's avatar
fabian serin committed
40
41
42
43
44
45
46
47
48
49
50
51
validation_error_definition["properties"] = {
    "loc": {
        "title": "Location", "type": "array", "items": {
            "oneOf": [
                {"type": "string"},
                {"type": "integer"}
            ]
        }
    },
    "msg": {"title": "Message", "type": "string"},
    "type": {"title": "Error Type", "type": "string"},
}
52
53
54
55
56
57
validation_error_response_definition["properties"] = {
    "errors": {
        "title": "Errors",
        "type": "array",
        "items": {"$ref": "{0}ValidationError".format(REF_PREFIX)},
    },
Luc Yriarte's avatar
Luc Yriarte committed
58
}