Skip to content

Instantly share code, notes, and snippets.

@ynwd
Created January 13, 2020 08:19
Show Gist options
  • Save ynwd/7c302979a101d7533c48d8371b47329f to your computer and use it in GitHub Desktop.
Save ynwd/7c302979a101d7533c48d8371b47329f to your computer and use it in GitHub Desktop.
UnhandledPromiseRejectionWarning Error Handling

UnhandledPromiseRejectionWarning Error Handling

(node:15701) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). (rejection id: 1)

Solution:

const checkFirstName = async (firstName) => {
  try {
    if (firstName === null || firstName === undefined) {
      throw new Error('Empty firstName')
    }
    return Promise.resolve(firstName)
  } catch (error) {
    return Promise.reject(error)
  }
}

const checkLastName = async (lastName) => {
  try {
    if (lastName === null || lastName === undefined) {
      throw new Error('Empty lastName')
    }
    return Promise.resolve(lastName)
  } catch (error) {
    return Promise.reject(error)
  }
}

const nameChecker = async (firstName, lastName) => {
  try {
    await checkFirstName(firstName)
    await checkLastName(lastName)
    console.log(`Name: ${firstName} ${lastName}`)
  } catch (error) {
    console.log(error)
  }
}

nameChecker()

Run:

$ node error_handling.js

Output:

Error: Empty firstName
    at checkFirstName (/Users/yanu/Documents/ismaya/api/error_handling.js:4:13)
    at nameChecker (/Users/yanu/Documents/ismaya/api/error_handling.js:25:11)
    at Object.<anonymous> (/Users/yanu/Documents/ismaya/api/error_handling.js:33:1)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment