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

113
Visualizações
Should use custom Error object instead of default one?

What are the pros and cons of using the default Error object this way? If I can already use it like this, why should I create custom error object (class CustomError extends Error {...})?

import express from 'express';
const app = express();

// routes
app.get('/one', (req, res, next) => {
  const error = new Error();
  error.code = 400;
  error.message = 'Any error message for /one';
  next(error);
});

app.get('/two', (req, res, next) => {
// Async example
  setTimeout(() => {
    try {
      throw new Error();
    } catch (error) {
      error.code = 403;
      error.message = 'Any error message for /two';
      next(error);
    }
  }, 1000);
});

app.get('/three', (req, res, next) => {
  throw new Error('Random unexpected');
});

// error handling middlewares
app.use((error, req, res, next) => {
  console.log('ERROR LOGGER');
  console.log('Date: ', new Date(Date.now()).toLocaleString());
  console.log('Path: ', req.path);
  console.log('Status Code: ', error.code || 500);
  console.log('Message: ', error.message || 'internal server error');
  console.log('Error: ', error);
  next(error);
});
app.use((error, req, res, next) => {
  res.status(error.code || 500).json({ code: res.statusCode, message: error.message || 'internal server error' });
});

// Listen Port
app.listen(3000);

Responses and Logs:

/one

enter image description here enter image description here

/two

enter image description here enter image description here

/three

enter image description here enter image description here

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

0

By creating such a custom Error object

class HttpError extends Error {
  constructor(name, code, message) {
    super();
    this.name = name;
    this.code = code;
    this.message = message;
  }
}

export default HttpError;

has the advantage of both having central control and preventing excessive repetition:

import HttpError from './HttpError.js';
.
.
.
app.get('/one', (req, res, next) => {
  next(new HttpError('Name errOne', 400, 'Any error message for /one'));
});
.
.
app.get('/two', (req, res, next) => {
// Async example
  setTimeout(() => {
    try {
      throw new HttpError('Name errTwo', 403, 'Any error message for /two');
    } catch (error) {
      next(error);
    }
  }, 1000);
});
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