1

On a NodeJs project, I call my async function this way:

const response = await myFunction();

Here's the definition of the function:

myFunction = async () => {
    return await new Promise((next, fail) => {
        // ...

        axios({
            method: 'get',
            url: apiEndpoint,
            data: payload
        }).then(function (response) {
            // ...

            next(orderId);
        }).catch(function (error) {
            fail(error);
        });
    });
}

How should I correctly intercept an error if that's happens? i.e. how I manage it when I await the function?

EDIT: as requested, a more complete snippet:

import express from 'express';
import { helpers } from '../helpers.js';

const router = express.Router();

router.post('/createOrder', helpers.restAuthorize, async (req, res) => {
    // ...
    const orderId = await api.createOrder();
    let order = {
        buyOrderId: orderId
    }
    
    const placed = await api.checkPlaced(orderId);
    if (placed) {
        let ack = await api.putAck(orderId);
        order.checksum = placed.checksum;
        order.ack = ack;
    }

    InternalOrder.create(order, (error, data) => {
        if (error) {
            return res.status(500).send({ message: error });
        } else {
            res.json("ok");
        }
    })
})

export { router as exchangeRouter }
markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 2
    I'm pretty sure `return await new Promise` is unneeded here? If you're using async/await you shouldn't need `.then` at all. consider using try/catch – evolutionxbox Jun 28 '22 at 14:15
  • 3
    Have you tried `try { ... } catch( err ) { ... }` ? Iirc, that works when `await`ing stuff. – Shilly Jun 28 '22 at 14:16
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jun 28 '22 at 15:44
  • Looks like a duplicate of [Correct Try...Catch Syntax Using Async/Await](https://stackoverflow.com/q/44663864/1048572), but I'm not quite sure what you are asking. What do you want to do with the "intercepted" error? – Bergi Jun 28 '22 at 15:50
  • @Bergi the then() solution is horrible to manage when you have a cascade of function that need to execute one after the other... – markzzz Jun 28 '22 at 16:16
  • @markzzz It would help if you could post your actual code then – Bergi Jun 28 '22 at 16:41
  • @Bergi: added a minimal example. Of course the amount of chain call could be increase on other section. The imporant is that each function will execute one after the other (both have new Promise). What I need to manage is an eventual error on each function (returning a sort of res.status(500) in case of error). – markzzz Jun 28 '22 at 18:31
  • @markzzz You don't need to write any `try`/`catch` yourself for that, [Express 5 will by default handle the promise rejection of the `async` route](https://expressjs.com/en/guide/error-handling.html) and will send a 500 error. – Bergi Jun 28 '22 at 19:39
  • @Bergi what if I need to manage the exception? Such as not return 500, or filter error data and do different action, and so on... – markzzz Jun 28 '22 at 19:43
  • @markzzz Then just write a `try`/`catch` block around the part from which you want to handle the error. But I still don't see how you'd have 4 nested blocks because of that. – Bergi Jun 28 '22 at 19:45
  • btw, you should really promisify that `InternalOrder.create` call – Bergi Jun 28 '22 at 19:46
  • @Bergi not able to catch the error. Is it correct to do that fail(error)? – markzzz Jun 29 '22 at 12:51
  • Not able to catch which error? What are the `api` methods and `InternalOrder.create`, where and how are they defined? – Bergi Jun 29 '22 at 12:52
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/246022/discussion-between-markzzz-and-bergi). – markzzz Jun 29 '22 at 12:53

1 Answers1

-1

Use try/catch:

let response;
try {
   response = await myFunction();
} catch (error) {
  // Handle error here.
}
Volodymyr Sichka
  • 531
  • 4
  • 10
  • if I have lots of async/await call in chain, this will flood the nested blocks within each try catch, which I don't like... – markzzz Jun 28 '22 at 14:34
  • 1
    @markzzz Are you really *handling* that many different errors in nested blocks? – Bergi Jun 28 '22 at 15:52
  • @Bergi I'm handling 3/4 call on a chain. 4 nested block are not so good imo – markzzz Jun 28 '22 at 16:13