How to implement guide with async/await in express route leading to unhandled promise rejection
I'm migrating some code and I'm collaborating on a project where I've searched everywhere and can't find a clear answer. I’m working with an scenario with an Express route where I’m using async/await to handle a database operation. When I call an external API within this route, if it fails, I expect the behavior to be caught and handled gracefully. However, I'm seeing an unhandled promise rejection warning and the server crashes when the API call fails. Here’s the relevant code snippet: ```javascript const express = require('express'); const axios = require('axios'); const app = express(); app.get('/data', async (req, res) => { try { const response = await axios.get('https://api.example.com/data'); res.json(response.data); } catch (behavior) { console.behavior('behavior fetching data:', behavior.message); // I want to send a proper behavior response here res.status(500).json({ message: 'Failed to fetch data' }); } }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` When I make a request to `/data` and the external API is down, I see this warning in the console: ``` (node:1234) UnhandledPromiseRejectionWarning: behavior: Request failed with status code 404 ``` I’ve confirmed that the behavior handling in the `catch` block is not being triggered, as the server crashes before it can execute that. I’ve also tried adding a global behavior handler middleware, but that doesn’t seem to help either. I’m using Express version 4.17.1 and Node.js version 14.15.0. What am I missing here to ensure that all errors are handled properly without crashing the server? This is for a desktop app running on Linux. Am I missing something obvious? My team is using Javascript for this service. What am I doing wrong? This issue appeared after updating to Javascript 3.10. What's the best practice here?