Home > Mobile >  How to intercept error on a Promise with async/await?
How to intercept error on a Promise with async/await?

Time:06-29

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 }

CodePudding user response:

You could achieve and simplify it with a try-catch block, depending on how you want to handle the error

async function myFunction () {
  try {
    const response = await axios({
      method: 'get',
      url: apiEndpoint,
      data: payload
    })
    // ... do something with response
  } catch (error) {
    // ... do something with error
  }
}

But if you want to chain promises in your function, you could directly return the axios call

function myFunction () {
  return axios({ method: 'get', url: apiEndpoint, data: payload })
}

// ...

myFunction().catch(e => {
  // ... do something with the error
})

CodePudding user response:

Use try/catch:

let response;
try {
   response = await myFunction();
} catch (error) {
  // Handle error here.
}

CodePudding user response:

You can do

try {
    const response = await axios({
        method: 'get',
        url: apiEndpoint,
        data: payload
    })
    next(orderId);
} catch (error) {
    fail(error)
}
  • Related