UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:#)错误:200

时间:2018-05-27 07:43:53

标签: node.js fetch

通过iTunes商店运行我的提取请求时 从https://itunes.apple.com/us/rss/topmovies/limit=20/json

获取iTunes上的热门电影列表
const fetch = require('node-fetch');

module.exports = function (app) {
    //Get homepage
    app.get('/', async (req, res) => {
        const url = 'https://itunes.apple.com/us/rss/topmovies/limit=20/json';
        const movie = req.params.id
        const movieResult = await fetch(url);
        const statusCodeIs200Or300 = movieResult.ok;
        const movieError = movieResult.statusText;
        const movieJson = await movieResult.json();
        const movieToRender = movieJson.feed.entry;
        console.log(movieResult.ok);
        if (movieResult.status == 200) {
          res.render('home', { movies: movieToRender});
        }
        throw new Error(movieResult.status);
    });

    // Get route for each specific the movies
    app.get('/movie/:id', async (req, res) => {
        const url = 'https://itunes.apple.com/us/rss/topmovies/limit=20/json';
        const movie = req.params.id
        const movieResult = await fetch(url)
        const statusCodeIs200Or300 = movieResult.ok
        const movieError = movieResult.statusText
        const movieJson = await movieResult.json()
        const movieToRender = movieJson.feed.entry[movie]
        // if statetement
        if (movieResult.status == 200) {
          res.render('modal', { movie: movieToRender})
        }
        throw new Error(movieResult.status);
    });


}

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:#)错误:200

请帮我解决此错误

2 个答案:

答案 0 :(得分:1)

错误只是声明您没有处理拒绝部分 在正常的承诺中, .catch()部分如下

new Promise(function(resolve, reject) {
  resolve('Success');
  //reject('err)
})
.then(function(value) {
console.log("everything ok")
})
.catch(function(e) {
  console.log(e); // "oh, no!"
})

但在异步等待发生错误时会发生什么? 你可以做以下其中一个

try {
      await  await fetch(url)
    } catch (err) {
      //handle error 
    }

或 也许像这样的中间件

const express = require('express');

const app = express();

app.get('/', safeHandler(handler));

app.listen(3000);

function safeHandler(handler) {
  return function(req, res) {
    handler(req, res).catch(error => res.status(500).send(error.message));
  };
}

async function handler(req, res) {
  await new Promise((resolve, reject) => reject(new Error('Hang!')));
  res.send('Hello, World!');
}

后一部分是由此来源safe handler solution

拍摄的

答案 1 :(得分:1)

Fadi的回答解释了如何正确处理承诺上的异常,但在您的情况下,您还需要从函数中返回一些内容,否则它将始终抛出错误:

app.get('/', async (req, res) => {
    const url = 'https://itunes.apple.com/us/rss/topmovies/limit=20/json';
    const movie = req.params.id
    const movieResult = await fetch(url);
    const statusCodeIs200Or300 = movieResult.ok;
    const movieError = movieResult.statusText;
    const movieJson = await movieResult.json();
    const movieToRender = movieJson.feed.entry;
    console.log(movieResult.ok);
    if (movieResult.status == 200) {
      // here you should return something to handle the case were all is good else the execution is going to continue and move onto to throw an exception. 
      return res.render('home', { movies: movieToRender});
     // this should do the trick and in case your rendering function return an error it would be propagated as well.
    }
    throw new Error(movieResult.status);
});

结合正确的错误处理,它会给出类似的东西:

app.get('/', async (req, res) => {
    const url = 'https://itunes.apple.com/us/rss/topmovies/limit=20/json';
    const movie = req.params.id
    try {
        const movieResult = await fetch(url);
        const statusCodeIs200Or300 = movieResult.ok;
        const movieError = movieResult.statusText;
        const movieJson = await movieResult.json();
        const movieToRender = movieJson.feed.entry;
        console.log(movieResult.ok);
        if (movieResult.status == 200) {
            return res.render('home', { movies: movieToRender});
        }
        throw new Error(movieResult.status);
    } catch (err) {
        // handle the error correctly here: e.g. use an error template
        res.status(500).send(error.message);
    }
});