What is the best way to return response errors in a function inside other function?

I have one function that call other functions, inside this functions may occur errors and i need to return the response.error()
but what is the best way to do this when is a function inside other function?

Example: i have this function:

async index({auth, response}) {

  // Busca os dados do usuário que está solicitando quiz

  const usuarioEstudante = await auth.getUser();

  // Através dos dados do usuário busca os dados do estudante

  const estudanteQuiz = await Student.query()

   .where("code", usuarioEstudante.username)

  const quizResponse = await this.verificaQuizAbertos(estudanteQuiz.id, response);

  return quizResponse;


And in the function verificaQuizAbertos:

async verificaQuizAbertos(idEstudante, response) {

  return await this.geraQuiz(idEstudante, null, response);


And in this third function may be occur errors and i need to return the response error:

async geraQuiz(idEstudante, quizAbertos, response) {

 const idsClassesEstudante = await this.getIdClassesEstudante(idEstudante);
      return response
      .json({ message: "Error" });

As you can see, nowadays i have to pass to third functions the response of the first function to each next function, there’s a better way to return responses in third functions?

1 Like

Eu acho que a tua função geraQuiz deveria retornar getIdClassesEstudante(idEstudante).
Aí, lá no index, tu verifica o response.

I solved with try/catch, in my first function i do:


   const quizResponse = await this.verificaQuizAbertos(estudanteQuiz.id);

   return quizResponse;


   return response.status(e.status)

   .json({errorMessage: e.errorMessage});


so in the other functions i can throw a error when it occurs, like:


   throw ({ errorMessage: 'Usuário precisa estar vinculado em uma classe', status: 500 })

Well, that’s actually a bad way to solve the problem. A better way would be use custom exceptions, they provide method in which you can handle the http request. Something like this:

const { LogicalException } = require('@adonisjs/generic-exceptions')

class CustomException extends LogicalException {
  handle (error, { response }) {
      .send('Custom exception handled!')

module.exports = CustomException

And for use it into the function you would do something like this

const NotEditableException = use('App/Exceptions/NotEditableException')

function example(){
     throw new NotEditableException()

Only use try/catch if you need to perform some action on the error before returning a response else use the global exception handler as recommended by @MarcoMacedoP

1 Like

if i understand in this case i will continue using try/catch but with custom exceptions that i will declare in other archives?

You can omit the try/catch. In the custom exception you can handle the http request by itself.

1 Like

thanks, i will try to implement this later