简体   繁体   English

nodejs api请求函数错误处理崩溃应用

[英]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.我正在尝试进行 api 调用并将其传递给将其存储到 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.我所有的其他函数都可以工作,只是包含 api 调用的请求函数不起作用。

Instead of redirecting, I only get the error messages in the terminal.我没有重定向,而是只在终端中收到错误消息。

Here's my code for it:这是我的代码:

index.js 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应用程序.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这是应用程序崩溃时我的终端的外观:终端错误消息

You have not describe what to do if an error occurs in the else statement of the request call.如果request调用的 else 语句中发生错误,您还没有描述该怎么做。 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:由于您在回调中使用async...await来插入数据库,因此您可以通过将其包装在try...catch中并将重定向移动到 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.但是, throw new Error('type error')仍然会导致应用程序在此处崩溃。 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:如果您还想在这种情况下重定向,那么您也可以在那里添加res.redirect('/')而不是抛出,或者将整个request调用包装在try...catch中,以便 catch 块也将捕获抛出的类型错误:

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('/')
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM