Use if() inside . catch() - error: Unexpected token if

Asked

Viewed 167 times

3

Is the following

I am new to javascript and I am not able to handle this error. I am trying to call a function and putting a .catch() to avoid error UnhandledPromiseRejectionWarning soon after it, but would like to make a check of 'if an error occurs, do so'.

I tried to do this check using a if(), but my console stops due to Syntaxerror: Unexpected token if. I’ve tried to use try...catch, but error occurred UnhandledPromiseRejectionWarning that I spoke... My code resembles this:

    //um pouco de código aqui

    function(args).catch(error => console.log(error),
    if(error){
         //Código que deve ser executado caso ocorra erro
    });

    //um pouco mais de código aqui

In short, it is possible to put a if() within a .catch()? Is there a better way to make this check?

1 answer

3


The arrow function syntax (Arrow Function) is wrong. You can do this (assuming that this function returns a Promise):

minhaFn('foo').catch(error => {
    if(error){
         console.log(error);
         // Outro código que deve ser executado caso ocorra erro
    }
});

Example: https://jsfiddle.net/zkodkf7b/

function minhaFn(nr) {
    return new Promise((resolve, reject) => {
        // isto vai dar asneira pois a variavel "naodeclarado" não está declarada
        resolve(nr / naodeclarado);
    });
}

minhaFn(20).catch(err => {
    if (err) {
        console.log(err);
        if (err.message.includes('is not defined')) {
            alert('Há variáveis não defenidas!');
        }
    }
}).then(res => console.log(res))

  • 1

    Thanks a lot, Sergio! You got me out of a jam =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.