question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

HTTP_500_INTERNAL_SERVER_ERROR cause a CORS error on frontend

See original GitHub issue

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.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

all code is in Description

Description

It is hard to show all main code of my project, I would show part of my code below.

  1. I already processed CORS in fastapi, I am sure it work when axios request is successful.
app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
)
  1. My way to handle global exception is adding a middlware, and when my code raise a AttributeError by itself, frontend would get a CORS error and axios shows that error.response is undefined
@app.middleware('http')
    async def catch_exceptions_middleware(request: Request, call_next):
        try:
            return await call_next(request)
        except Exception as e:
            # from fastapi.responses import JSONResponse
            # from fastapi import status
            logger.debug(f"middware catch the error")
            return JSONResponse(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                content="Unknow Error"
            )

image

  1. But when I use exception_handler to catch the certain exception, there is no CORS error, and axios shows error.response successfully. Sadly, it cound not work well to catch all the other exception when i use @app.exception_handler(Exception)
@app.exception_handler(AttributeError)
    async def all_exception_handler(request: Request, exc: Exception):
        # from fastapi.responses import JSONResponse
        # from fastapi import status
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content="Unknow Error"
        )

image

  1. By all above, my question is , how cound I catch a global exception to ensure that there is no CORS error on frontend?

Operating System

Windows

Operating System Details

win10 uvicorn 0.15.0 starlette 0.16.0

FastAPI Version

0.70.0

Python Version

Python 3.7.10

Additional Context

No response

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
tarasBilobrancommented, Nov 6, 2021

Had the same problem, thanks. Could someone please ping me once there will be an official fix?

2reactions
uriyyocommented, Oct 25, 2021

I believe it’s a bug.

As a temporary workaround, you can add ServerErrorMiddleware middleware with global exc handler before all middlewares:

from starlette.middleware.errors import ServerErrorMiddleware
from starlette.requests import Request
from starlette.types import ASGIApp

from fastapi import FastAPI, status
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse


async def global_execution_handler(request: Request, exc: Exception) -> ASGIApp:
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content="Unknown Error",
    )


app = FastAPI()
app.add_middleware(
    ServerErrorMiddleware,
    handler=global_execution_handler,
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Read more comments on GitHub >

github_iconTop Results From Across the Web

CORS policy: No 'Access-Control-Allow-Origin' / 500 (Internal ...
Your server should accept all routes that the client can ask for with the ... the browser terminates the request, resulting in a...
Read more >
[QUESTION] cors and error status 500 and handle it in frontend
If you receive a 500 response that means you have an error in your backend app code (Python using FastAPI). It doesn't have...
Read more >
Troubleshoot CORS errors from API Gateway - Amazon AWS
Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard.
Read more >
CORS Implementation, got error 500 (Internal Server Error)
I got rid of the error by using Access-Control-Allow-Origin header in web.config following some other site advised. But my real problem is,. I ......
Read more >
What Is a CORS Error and How to Fix It (3 Ways) - Bannerbear
A CORS error is common when making an HTTP request to another origin. You can get rid of it using one of the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found