'How to customize a Bad Request response in Firebase functions

I wrote a simple Firebase function like below

exports.simpleFunc = functions.https.onRequest((req, res) => {
    
    try{
        JSON.parse(req.body);
        res.send('Valid');
    }
    catch(error){
        res.send('JSON is invalid');
    }
});

then I ran this function locally by using firebase emulator:start

after that I used Postman to test this function by sending an invalid JSON values

{
    "firstName": "User 1",
    "email": "[email protected]",
    "description": "\u000g" >> this is an invalid value
}

I expect that my function should return my error message JSON is invalid. However it returned a whole HTML page with an error SyntaxError: Unexpected token g in JSON at position xx at JSON.parse (<anonymous>)

So my question is: How can I send my error message instead of the whole HTML string?

I have found the same issue here https://github.com/firebase/firebase-functions/issues/364

But it's not my expectation.



Solution 1:[1]

There's no way you can expect to catch the error parsing of JSON if you declared it as JSON. To catch it, instead of declaring as JSON, declare it as text and parse it on the client. See images below for reference.

Declaring it as JSON (See green highlighted section): enter image description here

Declaring it as Text (See green highlighted section): enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marc Anthony B