handling PromiseRejection in node.js

Viewed 140

I've just started working with javascript for the first time. From googling I have only been able to find examples of handling promise rejection through functions that have been written by you. My problem is that

app.getInput("key");

is not written by me. I want to be able to handle the rejected promise in my code. My brain is having trouble "getting javascript" at the moment.

I have this function (in the jovo framework)

var content = app.getInput('content');

I get the error "TypeError: Cannot read property 'content' of undefined". I know why I'm getting this error, I just want to be able to handle the situation where there is no content.

It says also "UnhandledPromiseRejectionWarning: Unhandled promise rejection"

I just want to be able to write something like

var content = "null";

content = testFunc().then(() => {
    console.log('resolved content!');
}).catch((err) => {
    console.log('error content');
    content = "null";
});

function testFunc(){
    return app.getInput('content');
}
3 Answers

It's weird that an non asynchronous method return an error that way. Anyway, now how to handle it


Wrap it with try/catch

let content;

try {
   content = app.getInput('content');

   // All is ok there

   ...
} catch (err) {
  ...
}


@Gabriel Bleu

function a() {
  throw new Error('Error');
}

async function testFunc() {
  try {
    const content = a();
    
    console.log('No error');
    
    return content;
  } catch(err) {
    console.log('Error');
  
    return null;
  }
}

testFunc();

Easiest way to deal with promise is using async/await

async function testFunc() {
  try {
    const content = await app.getInput('content');
    return content;
  } catch(err) {
    return null;
  }
}

From your description and from jovo docs, I understand that getInput() is a synchronous method. The error TypeError: Cannot read property 'content' of undefined is being thrown to the caller (your code). Looks like the framework isn't properly initialized, the undefined thing leads me to believe that.

As Grégory NEUT answered earlier, you use a try/catch block to handle it.

try {
  content = app.getInput('content');

  // All is ok there
} catch (err) {
  // content is unavailable, inspect the error
}

The other issue, "UnhandledPromiseRejectionWarning: Unhandled promise rejection" happens when a promise is rejected and not caught. Perhaps the try/catch would solve this, but perhaps not. The fact is that when you call testFunc() and it fails, it doesn't returns a rejected promise, so it won't have a method .then() as you expected. Gabriel Bleu solution would make sure you'll get back a promise in any case.

Related