Source: Fastapi change error measage

← Rendered

markdown source:

---
description: Переопределение текста ошибок в fastapi
tags: fastapi python
title: Fastapi change error measage
---
В фастапи сообщение ошибки выглядит примерно так

```json
{"detail": [
{
    "loc": [
        "body",
        "location",
        "name"
    ],
    "msg": "field required",
    "type": "value_error.missing"
},
{
    "loc": [
        "body",
        "location",
        "name12"
    ],
    "msg": "extra fields not permitted",
    "type": "value_error.extra"
}
]
}
```

Текст ошибки задан в `fastapi.exceptions`. Класс можно переопределить

```python
from fastapi import Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel

@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder({"detail": exc.errors(),
                "body": exc.body,
                 "your_additional_errors": {"Will be": "Inside", "This":" Error message"}}),
    )

class Item(BaseModel):
    title: str
    size: int

@app.post("/items/")
async def create_item(item: Item):
    return item
```

Теперь передав в body

```json
{
 "title": 22,
 "size": "hehe"
}
```

Мы получим ответ

```json
{
  "detail": [
    {
      "loc": [
        "body",
        "size"
      ],
      "msg": "value is not a valid integer",
      "type": "type_error.integer"
    }
  ],
  "body": {
    "title": 22,
    "size": "hehe"
  },
  "your_additional_errors": {
    "Will be": "Inside the",
    "Error": "Message"
  }
}
```

[Другой вариант](https://stackoverflow.com/a/60274832) - через [[fastapi-middleware]]

- [[fastapi]]
- [[fastapi-requests-errors]]
- [[http-requests-errors]]
- [[starlete-список-кодов]]


[fastapi-middleware]: fastapi-middleware "Fastapi middleware"
[fastapi]: fastapi "Fastapi"
[fastapi-requests-errors]: fastapi-requests-errors "Fastapi requests errors"
[http-requests-errors]: http-requests-errors "Http requests"
[starlete-список-кодов]: starlete-%D1%81%D0%BF%D0%B8%D1%81%D0%BE%D0%BA-%D0%BA%D0%BE%D0%B4%D0%BE%D0%B2 "Starlette список кодов"