Replies: 3 comments 1 reply
-
So, the background tasks are attached to the response. Once the response is sent successfully, all the background tasks are executed. But raising an exception is a way of saying "stop and abort everything here, something was wrong", so, the original response (that is what contains the background tasks) is never returned, and those background tasks are never executed. I think I can imagine how it could be useful to run background tasks after raising something, but I can also see how the current default behavior could still be useful. I see 2 alternatives to solve your use case. One is to return a response directly, with a status code of 400. The benefit of raising is just that it aborts anything else, so it can be used even inside of deeply nested dependencies. But in the end, it is just converted to a normal response using a status code of 400, so you could just return it directly. The other option is to create your own custom exception that could include some background tasks and raise it. And then use a custom handler to get the exception, extract the background tasks, and return any relevant response with its custom background tasks: https://fastapi.tiangolo.com/tutorial/handling-errors/#install-custom-exception-handlers |
Beta Was this translation helpful? Give feedback.
-
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
-
thank you for your answer, can you please emphasis this in the docs please i spent too much time on a pblm that raise an exception and abort the background tasks if only this was clearer at least for people like me ...and really man thank you for evthg ur awesome |
Beta Was this translation helpful? Give feedback.
-
First check
Description
Currently, I am trying to implement an email verfication resource which automatically sends a new email using SendGrid (using the SendGrid API client). The email is created but the
send_sendgrid
task is never executed. The setting works just fine when I am using the setup as described in the documentation and returning a response. Is it possible that the thread is killed after callingraise
? Is there any possibilty to execute the email function as a background task although usingraise
?Additional context
Beta Was this translation helpful? Give feedback.
All reactions