user1657666
user1657666

Reputation: 451

How pass "reason" when we use the HTTPException with FASTAPI?

I have an API based on FAST API that, when something goes wrong raises the following exception.

            raise HTTPException(status_code=404, detail="There is no file to created a zip package. Check device name.")

As you can see I included the detail field, however, observing the logs I see the following


[2023-12-15 00:16:30,954]:[DEBUG]:[file_operations]:download_log_file() error: 404 reason:Not Found

Why the reason is "Not Found" ? Is there anything wrong with the code? The code that captures this log is based on request as you see below:

 try:
            r = self.get(
                self.base_url + "/downloadlog",
                headers=headers,
                params=params,
                timeout=100,
            ) 
            
              # Check if the request was successful (status code 200)
            if r.status_code == 200:
                   ...
                   ...
            else:
                
                print(f"download_log_file() error: {r.status_code} reason:{r.reason}")

                error_response = {
                    "error": f"HTTP error occurred: {r.status_code} {r.reason}",
                    "request_id": request_id,
                }
                raise HTTPException(
                    status_code=r.status_code, detail=error_response
                )

Upvotes: 0

Views: 479

Answers (2)

Yurii Motov
Yurii Motov

Reputation: 2268

You can print more detailed information about Exceptions by setting exception handlers:

from fastapi import FastAPI
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: StarletteHTTPException):
    print(f"{exc.__class__.__name__}: {repr(exc.detail)}")
    return await http_exception_handler(request, exc)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc: RequestValidationError):
    print(f"Request validation error: {exc}")
    return await request_validation_exception_handler(request, exc)

@app.get("/")
def index():
    HTTPException(status_code=400, detail="Details...")

I think it's also possible to override FastAPI logger's message format, but I didn't manage to figure out how to do it.

Upvotes: 0

joyanedel
joyanedel

Reputation: 21

As far as I understand how FastAPI handles HTTPException, the reason why you're observing Not found message your logger is because FastAPI takes the status code you sent by parameter, search for the error definition using http library (see https://docs.python.org/3/library/http.html for further information) and logging it

The detail you are specifying is sent directly to the client as you can see in the documentation of FastAPI: https://fastapi.tiangolo.com/tutorial/handling-errors/#import-httpexception (link to the exact section where this is explained better)

Upvotes: 0

Related Questions