Amarjit Singh
Amarjit Singh

Reputation: 2154

send error message back to browser in nodejs

I have a node API that is working fine when tested using postman. But when I use this API in my angular project there occurs an error and browser don't get any response there it keep waiting for a response. When I go to console I see the error message.

How I can make that error message to be sent back to the browser with full stack trace

Upvotes: 1

Views: 1605

Answers (1)

GaryL
GaryL

Reputation: 1460

In general, you will need to catch that error, then populate http response object with it just the same as if you were sending successful response data back to the requestor.

Synchronous processing:

try {
   // do my requested stuff
   res.status(200).json({something:"returned"}); 
} catch(ex) {
   res.status(500).json(ex); 
};

Promises:

Promise.resolve()
    .then(() => {
         // do my requested stuff
         // return my results stuff to the client
         res.status(200).json({something:"returned"}); 
    })
    .catch((ex) => {
        // return 500 error and exception data to the client
        res.status(500).json(ex);  
    });

Also, as standard practice you should catch all errors, and at the very least, you should return a 500 to the browser res.status(500) so you don't leave it hanging when unexpected issues arise.

And, of course you can return html rather than json, and/or more info in the response.

Good luck.

Upvotes: 3

Related Questions