Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Empty message about raised exception in documentation code example (Handling Errors) #1814

@manlix

Description

@manlix

Issue description

I have tried to run example code from documentation (section Handling Errors) and got empty message in console logs about raised exception (HTTPException).

Actual and unexpected result in logs — no details about raised exception:

OMG! An HTTP error!: 
INFO:     127.0.0.1:50364 - "GET /items/3 HTTP/1.1" 418 

Expected result — with details about raised exception:

OMG! An HTTP error!: HTTPException(status_code=418, detail="Nope! I don't like 3.")
INFO:     127.0.0.1:50364 - "GET /items/3 HTTP/1.1" 418

Code from documentation:

from fastapi import FastAPI, HTTPException
from fastapi.exception_handlers import (
    http_exception_handler,
    request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException

app = FastAPI()


@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
    print(f"OMG! An HTTP error!: {exc}")
    return await http_exception_handler(request, exc)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    print(f"OMG! The client sent invalid data!: {exc}")
    return await request_validation_exception_handler(request, exc)


@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id == 3:
        raise HTTPException(status_code=418, detail="Nope! I don't like 3.")
    return {"item_id": item_id}

How to reproduce:

Run in console:

manlix@lab:~$ curl http://localhost:8000/items/3
{"detail":"Nope! I don't like 3."}

The cause of the problem:

Starlette's HTTPException hasn't __str__() method:

class HTTPException(Exception):
    def __init__(self, status_code: int, detail: str = None) -> None:
        if detail is None:
            detail = http.HTTPStatus(status_code).phrase
        self.status_code = status_code
        self.detail = detail

    def __repr__(self) -> str:
        class_name = self.__class__.__name__
        return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions