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

3

It is as follows

I'm new to javascript and I'm not sure how to handle this error. I'm trying to call a function and putting a .catch() to avoid the error UnhandledPromiseRejectionWarning shortly after it, but I would like to check 'in case an error occurs, .

I tried to do this check using a if() , but my console for SyntaxError: unexpected token if . I have tried to use try...catch , but the error occurred UnhandledPromiseRejectionWarning I said ... My code looks like 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, is it possible to put if() within .catch() ? Is there a better way to do this?

    
asked by anonymous 25.01.2017 / 23:52

1 answer

3

The function syntax arrow ( arrow function ) is wrong. You can do this like this (assuming 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: link

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))
    
26.01.2017 / 00:04