Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
nodejs api request function error handling crashes app

I'm trying to make an api call and pass it into a function that stores it into mongodb. The problem is that the entire site crashes when I try to handle errors instead of redirecting to the error page. All my other functions work, it's just the request function containing the api call that doesn't.

Instead of redirecting, I only get the error messages in the terminal.

Here's my code for it:

index.js

router.post('/',async function(req,res){
  var {title,date,loc,count, save,del,update,csv} = req.body;
  var {username} = req.session;
  console.log(req.body);
  var url = `http://api.openweathermap.org/data/2.5/weather?q=${loc}&appid=${API_KEY}&units=metric`

  if(save){
    //weather api       
    request({ url: url, json: true }, async function (error, response) {
      if(error){
        throw new Error ('type error');
      }
      else{
        console.log('Current weather: '
                + response.body.main.temp
                + ' degrees celsius'
        );
        let w = JSON.stringify(response.body.main.temp);
        console.log(w)
        await db.addItem(username,title, loc, count, w, date);
      }
    });
    res.redirect('/');
  }  

app.js

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

Here is what my terminal looks like when the app crashes: terminal error message

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have not describe what to do if an error occurs in the else statement of the request call. So if an error occurs it will crash.

Since you are using async...await in the callback to insert into the db, you can get the functionality you want by wrapping it in a try...catch block and moving the redirect into the catch:

request({ url: url, json: true }, async function (error, response) {
  if(error){
    throw new Error ('type error');
   } else {
     try {
      console.log('Current weather: '
        + response.body.main.temp
        + ' degrees celsius'
      );
      let w = JSON.stringify(response.body.main.temp);
      console.log(w)
      await db.addItem(username,title, loc, count, w, date);
    } catch (error) {
      console.log(error);
      res.redirect('/');
    }
  }
});

However, the throw new Error('type error') will still cause the app to crash here. If you want to also redirect in this case, then you can add a res.redirect('/') there as well instead of throwing, or wrap the entire request call in a try...catch so that the catch block will also catch that thrown type error:

try {
   request({ url: url, json: true }, async function (error, response) {
      if(error){
        throw new Error ('type error');
      }
      else{
        console.log('Current weather: '
                + response.body.main.temp
                + ' degrees celsius'
        );
        let w = JSON.stringify(response.body.main.temp);
        console.log(w)
        await db.addItem(username,title, loc, count, w, date);
      }
    });
} catch (error) {
  res.redirect('/')
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda