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.

[QUESTION] Only 500 response being received from middleware [ INVALID ]

See original GitHub issue

First check

  • [ YES ] I used the GitHub search to find a similar issue and didn’t find it.
  • [ YES ] I searched the FastAPI documentation, with the integrated search.
  • [ YES ] I already searched in Google “How to X in FastAPI” and didn’t find any information.

Description

I am trying to use middleware for Authorization ( Like Express JS in Node ). My middleware throws an exception which I am trying to send a custom response ( like 401 ) for, But I am only receiving 500 from the server.

From what I understand, The “middleware” raises an internal error that is not being over-ridden by my custom response. How can I over-ride the middleware’s default 500 response and send my own response?

Additional context

The middleware is below:

@add.middleware("http") def validate_all_routes( request: Request, call_next): try: validate_route(request.headers) # Unauthenticated req --> Raises exception response = call_next(request) return { ... } # This return is received by client except Exception as e: return { "exception": "server_error" } # Not received by client raise HttpException(status_code=401) # Not received by client raise Response(status_code=401) # ONLY IF I DO THIS response = call_next(request) return { ... } # Is the response that I sent received `

Can someone please advise me on what I’m doing wrong and how I will be able to make the middleware send a custom response ( with custom HTTP_status) without invoking the

response = call_next(request)

Thanks for the help in advance! Let me know if I can provide any other context/ clues.

EDIT: I was facing 500 Internal Server Error because I did not use async on the function below the middleware ie @app.middleware('http'). Following @phy25’s comment on using `return Response(…) allows me to send a response with my own status_code

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
vancouverwillcommented, Apr 23, 2020

yeah not saying it is super important but it is less than ideal. Expected behaviour is to handle errors in a similar manner across the FastApi handling code otherwise have to manually create a 401 response in middleware and use different implementation if triggered elsewhere.

But maybe it’s because exceptions at the middleware level could be critical to the application and there should be no option for something unexpected here…

Regarding unexpected exceptions that does sound bad, I’m not saying all exceptions should be safely handled rather the inbuilt HTTPException class which contains status_code be handled the same way as in the query functions.

:edit or at least update the docs around eror handling to say they don’t apply to middleware https://fastapi.tiangolo.com/tutorial/handling-errors/

1reaction
phy25commented, Mar 17, 2020

Have you tried return Response(content="", status_code=401)?

Read more comments on GitHub >

github_iconTop Results From Across the Web

ASP.NET Core Response Caching Middleware - Stack Overflow
Response Caching Middleware only caches server responses that result in a 200 (OK) status code. Any other responses, including error pages, are ...
Read more >
How to fix HTTP 500 internal server error? - IONOS
The “Internal Server Error” can occur when the request is processed by the web server. The collective status code includes everything unplanned ...
Read more >
500 Internal Server Error | Apigee Edge
The HTTP status code 500 is a generic error response. It means that the server encountered an unexpected condition that prevented it from...
Read more >
Handling Web API Exceptions with ProblemDetails middleware
In this short post I describe a handy error-handling middleware, ... there's no exception middleware registered so you get a "raw" 500 ......
Read more >
Handle errors in ASP.NET Core web APIs - Microsoft Learn
Exception Handling Middleware can also be used in the Development ... A problem details response is generated with the previous code when ...
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