개발/JavaScript

JavaScript | UnhandledPromiseRejectionWarning: Error

AM0530 2020. 4. 22. 00:06

1. 에러 메세지 : UnhandledPromiseRejectionWarning

This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch(). 

 

2. 원인 : 

catch block을 안쓰고 throw error를 사용해서 발생

 

오류가 발생한 코드 

export const home = async (req, res) => {
    const videos = await Video.find({});
    throw Error("this is error");
};

 

 

3. 해결 : try - catch 를 블럭을 사용해서 error를 잡는다 

수정한 코드 

export const home = async (req, res) => {
  try{
    const videos = await Video.find({});
    throw Error("error");
    res.render("home", { pageTitle: "Home", videos});
  } catch(error){
    console.log(error);
    res.render("home", { pageTitle: "Home", videos: []});
  }
};

 

참고 :

- https://stackoverflow.com/questions/53940043/unhandledpromiserejectionwarning-this-error-originated-either-by-throwing-insid

 

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

I am getting following error in my Node-Express App UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function witho...

stackoverflow.com

- 노마드 코더 nodejs 강의

https://academy.nomadcoders.co/