Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
How to intercept error on a Promise with async/await?

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 }
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use try/catch:

let response;
try {
   response = await myFunction();
} catch (error) {
  // Handle error here.
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do

try {
    const response = await axios({
        method: 'get',
        url: apiEndpoint,
        data: payload
    })
    next(orderId);
} catch (error) {
    fail(error)
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda