Home > OS >  Is it possible to interrupt Javascript the flow of code with an Exception in NodeJs?
Is it possible to interrupt Javascript the flow of code with an Exception in NodeJs?

Time:01-01

In Java, I would be able to do something like this, and I'm wondering if anything like this is possible in NodeJS?

function is_document_redundant(document) {
    // pseudo code, not real
    result = mongoose.Model.find(document.id);
    if (result != null) {
        throw new RedundantDocumentException(document);
    }
}

function save_document(document) {
    // pseudo code, not real
    try {
        is_document_redundant(document);
        mongoose.Model.save(document);
    } catch(err) {    
        console.log(err)
    }    
}

To be clear, if this line throws an exception:

        is_document_redundant(document);

Then this line should never happen:

        mongoose.Model.save(document);

That is, the script basically ends once the Exception is thrown.

I tried writing this code, but sadly, the script seems to continue past the Exception. Even when the code is redundant, and this throws an exception:

        is_document_redundant(document);

The script still executes this line:

        mongoose.Model.save(document);

I've got redundant documents piling up in the database. I'm wondering how I can avoid this, without having to have a bunch of ugly catch() blocks everywhere. I'd rather have the exceptions bubble up to the top and handle them all in the one catch block, but I need those Exceptions to interrupt the code and take the flow of control directly to that top level catch() statement.

Edit:

Okay, now I'm trying to use await but:

I've an Express route that starts like this:

app.post('/ams', async (req, res) => {

    try {

and then tried:

            let is_redundant = await document_is_redundant(AMS_945, unique_id);
            console.log(is_redundant);

    if (is_redundant) {
                throw new DocumentIsRedundantException(unique_id);
            }

but I get:

SyntaxError: await is only valid in async function

CodePudding user response:

async function is_document_redundant(document) {
    // pseudo code, not real
    result = await mongoose.Model.find(document.id);
    return result != null
}

async function save_document(document) {
    // pseudo code, not real
      cosnt isRedundant = await is_document_redundant(document)
      if (isRedundant) {
        mongoose.Model.save(document);
        return res.send('success')
      } else {
        return res.status(404).('refused to save')
      }
}

If you just want different results, you don't necessarily need to rely on error.

In client-side, you can use res.ok to check if the response you received is not 200 status code. (try-catch in client-side does not work since handmake errors are not network errors)

  • Related