How to capture an exception of a function that is within a Try catch?

Asked

Viewed 30 times

1

I have this asynchronous method:

async printForNetwork( device ) {
    try {
        const options = {encoding: "860"};
        const printer = new Printer(device, options);

        device.open( err => {
            if (err)
                return err; // preciso lançar a exception desse erro

            printer.align('CT');
            printer.size(1, 2);
            printer.text('Teste');
            printer.close();
        });

    } catch (e) {
        throw e;
    }
}

I need to make an exception if the attribute err in device.open to treat it in catch.

but if I make a throw inside device.open the exception is not being captured.

  • Rafael, you cannot throw and treat the exception when consuming the method, consuming with then/catch?

  • That one try catch it has no sense, if you will just throw the exception, without any treatment, do not need it

1 answer

3

Maybe that’ll solve your problem:

async function printForNetwork( device ) {
try {
    // ...

    await Promise.resolve(device.open( err => {
        if (err) 
          throw err;

        // ...
    }));

} catch (e) {
    throw e;
}

}

Browser other questions tagged

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