We manage a backend application behind a FastAPI REST controller with multiple endpoints.
A member of our team decided to use a middleware on the application which parses the body of every incoming HTTP request after it has been processed by the application, see if there is any 'error' key in there (it assumes every response is a dictionary...), then sends a JSONResponse with status code 400.
They did this because the way errors are handled in the backend is by sending an 'error' message in the response, which most of the time is a dictionary. We received complaints from our clients because in this case the status code sent from the API was 200, even though it contained an error message.
I know there are so many things wrong in this approach, but I can't seem to find the words to give a constructive feedback as to why it's bad. All I can say is what's the good way to do it :
- All non-recoverable errors occurring in the backend should spark specific exceptions, and the controller should handle a set of reasonably generic exceptions as to what's the backend is supposed to be doing and send the right status code back to the client depending on those exceptions.
- Exceptions, handled or unhandled, will anyway propagate up to the top-level, which is the controller.
I'm looking for precise arguments to explain why the 'exception propagation' approach I suggested is better than using a middleware, for a constructive feedback.
NB: I'm also open for alternatives / constructive feedback if the latter approach is in fact wrong.