Skip to content

HTTPException from Starlette not converted to FastApi class #3383

@pgrandinetti

Description

@pgrandinetti

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google "How to X in FastAPI" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • Or, I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here's a self-contained minimal, reproducible, example with my use case:

import sys
import logging
from typing import Callable

from fastapi import Request, Response,\
        FastAPI, APIRouter, Depends, HTTPException
from fastapi.routing import APIRoute

from fastapi.security import APIKeyHeader

log = logging.getLogger(__name__)
logging.basicConfig(
    stream=sys.stdout,
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

class MyRouter(APIRoute):
    def get_route_handler(self) -> Callable:
        original_handler = super().get_route_handler()

        async def custom_route_handler(request: Request) -> Response:
            try:
                response = await original_handler(request)
            except Exception as exc:
                log.debug('### %s ###', type(exc))
                raise
            return response

        return custom_route_handler


my_sign = APIKeyHeader(name='A-Signature')


def my_auth(sign_header: str = Depends(my_sign)):
    if sign_header != 'xyz':
        raise HTTPException(403, detail='Signature not valid')


router = APIRouter(route_class=MyRouter,
                   prefix='/test',
                   dependencies=[Depends(my_auth)])


@router.get('')
async def get_test():
    return {'Hello': 'World'}


app = FastAPI()
app.include_router(router)

Description

I noticed that when the APIKeyHeader is missing (not sent from the client), the exception raised all the way up to through the stack is starlette.exceptions.HTTPException. I think it would be nice to have it as instance of fastapi.HTTPException

Steps to reproduce

$ pip install fastapi
$ pip install uvicorn
# save the code as issue.py
$ uvicorn issue:app --reload
$ curl localhost:8000/test
$ curl localhost:8000/test -H 'A-Signature: abc'

Then look at the logs in the uvicorn shell and will see the two exceptions have different types.

The solution you would like

I think it would be nice to have both exceptions as instances of fastapi.HTTPException.

Describe alternatives you've considered

I didn't consider any, and I am not sure if this is a wanted feature. Would be happy to try a PR with some guidance.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions