Reputation: 6535
Firebase HTTP Functions ships with pre-installed dependencies, namely body-parser
which will parse the request body based on the provided content-type.
So that if I call a Firebase HTTP Function with an invalid payload, i.e:
POST http://localhost:5000/example-project/us-central1/example
content-type: application/json
{
test
}
Firebase will send a 400 Bad Request
response:
TTP/1.1 400 Bad Request
x-powered-by: Express
content-security-policy: default-src 'none'
x-content-type-options: nosniff
content-type: text/html; charset=utf-8
content-length: 1012
date: Tue, 10 Dec 2019 15:38:46 GMT
connection: close
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>...</pre>
</body>
</html>
Before my code is being executed.
Google Cloud mention this in the documentation:
Cloud Functions automatically reads the request body, so you will always receive the body of a request independent of the content type. This means that HTTP requests should be considered to have been fully read by the time your code is executed. The nesting of ExpressJS apps should be used with this caveat—specifically, middleware that expects the body of a request to be unread might not behave as expected.
Since I am building a public facing API this is problematic for several reasons:
text/html
which is a mess to handle on the client side, and;Is there a way to handle errors that are thrown higher up in the process chain for Firebase HTTP Functions, or is this simply one of the caveats mentioned in the documentation?
I know that by not specifying the request content-type in the request I am able to parse it and throw what error I like but that is just poor implementation.
I found that there is an HttpsError
class in the Firebase documentation which seems to be the function that throws those responses. It has a toJSON
method which gives the error response as application/json
.
Upvotes: 0
Views: 109
Reputation: 317322
Cloud Functions is failing before your code is ever executed, because the client sent a value that is technically malformed. Hence, the HTTP 400 response. Unfortunately, you have no way to intercept this, as the service infrastructure is bailing out before the provided callback can be invoked, and there are no callbacks for handling these sorts of errors.
Upvotes: 1