Return statements in catch block of await-operations


#1

Hey guys,

AdonisJS recommends quiete accurate to take care of await-operations by wrap it between try/catch or a .catch() statement directly on the operation.

I tried the following test setup:

async test({request, response}) {

    const user = await User.findByOrFail("email", "john@doe9999.de").catch( error => {
      console.log(error);
      return response.status(400).json({error: error})
    })

    return response.status(200).json({user: user})
  }

The email does not exist and Adonis logs the error to the console, so the catch block is correctly accessed:

ModelNotFoundException: E_MISSING_DATABASE_ROW: Cannot find database row for User model
> More details: https://err.sh/adonisjs/errors/E_MISSING_DATABASE_ROW
    at Function.raise (...\node_modules\@adonisjs\lucid\src\Exceptions\index.js:143:12)
    at Proxy.firstOrFail (...\node_modules\@adonisjs\lucid\src\Lucid\QueryBuilder\index.js:434:39)
    at <anonymous>

As expected, the error return statement is assigned to const user.

But in my use case, I want to leave the complete function with returning the error or something else.
So how can I “exit” the complete async test() {...} function directly out of the catch block with a return? Is there a possibility to?

I would appreciate your help,
kind regards,
stoniemahonie


#2

Is this what you’re looking for?

    try {
      const user = await User.findByOrFail("email", "john@doe9999.de");
      return user;
    } catch(error) {
      return response.status(400).json({error: error})
      // or call another method / what ever
    }