Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
alternative to multiple try-catch blocks in a function

Imagine we have a function like so:

async function doSomethingWithFriends() { 

  let user, friends, friendsOfFriends = null;

   try { 
       user = await getUser();
   }  catch(err){
       return [401, err]
   } 

    try {
      friends = await getFriends(user); 
    } catch (err){
       return [500, err];
    }

    try {
      friendsOfFriends = await getFriendsOfFriends(friends); 
    } catch(err){
       return [500, err]
    }

    return doFriendsOfFriends(friendsOfFriends);
} 

instead is there some established pattern to avoid this somewhat boilerplate code?

There are two problems with the above code:

  1. it's noisy
  2. we cannot use const

One solution is to only use try-catch in the caller functions, but I am wondering if there is a way to solve it all the way down/up.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Are you using Expressjs or something ? Please provide more information. I will assume you are making an API.

You can create a middleware that would handle all the error in your controller. Then in your controller you only need to throw or pass the error into next middleware. Example below.

error handle middleware

export function errorHandlingController(error: ErrorRequestHandler, _req: Request, res: Response, _next: NextFunction): void {
    let errorCode: number
    if (error instanceof RequestPayloadError) {
        errorCode = 400
    } else if (error instanceof UnauthorizedError) {
        errorCode = 401
    } else if (error instanceof NotFoundError) {
        errorCode = 404
    } else {
        errorCode = 500
    }
    res.status(errorCode).json(<GeneralResponse>{
        status: responseStatus.error,
        message: error.toString()
    })
}

user controller

export function getMyProfile(_req: Request, res: Response, next: NextFunction): void {
    try {
        const user = res.locals.user
        if (!user) throw new UnauthorizedError('Author id not identified')
        res.status(200).json({
            status: responseStatus.success,
            user: user
        })
    } catch (error: unknown) {
        next(error)
    }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

In this case each function you can define custom exception. In doSomethingWithFriends only one try catch in used. Sample code below:

(async function doSomethingWithFriends() {


  async function getUser() {
    throw 'getUser'
  }

  async function getFriends() {
    throw 'getFriends'
  }

  async function getFriendsOfFriends() {
    throw 'getFriendsOfFriends'
  }

  let user, friends, friendsOfFriends = null;

  try {
    user = await getUser();
    friends = await getFriends(user);
    friendsOfFriends = await getFriendsOfFriends(friends);
  }  catch(err){
    console.log(err)
    if (err) {
      // custom return what you want
    }
  }

  return doFriendsOfFriends(friendsOfFriends);
}())

about 4 years ago · Juan Pablo Isaza Relatório

0

The catch phrase of Promise API can be combined with switch/if statements. Something like below (did not test it for syntax err etc.):

async function doSomethingWithFriends() {    
  let errID = 0;
  return getUser()
   .then(user => (++errID,getFriends(user)))
   .then(friends => (++errID, getFriendsOfFriends(friends)))
   .then(fof => (++errID, doFriendsOfFriends(fof)))
   .catch(err => {switch (errID) {
     case 0:
       return [401, err];
     case 1:
       return [500, err];
     ...
   }});
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda