Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
¿Cómo manejo los errores en la aplicación Node Express?

¿Hay alguna forma de agregar middleware o app.use() para detectar todos los posibles errores?

He probado algunos enfoques globales de intento y captura, pero parece muy frágil.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Mi enfoque sería como a continuación

Coloque debajo del código en

servidor.js o index.js

 class AppError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'; this.isOperational = true; Error.captureStackTrace(this, this.constructor); } } app.all('*', (req, res, next) => { next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404)); }); app.use((err, req, res, next) => { err.statusCode = err.statusCode || 500; err.status = err.status || 'error'; res.status(err.statusCode).json({ status: err.status, message: err.message }); }); app.use((req, res, next) => { console.log("Middleware 1 called.") console.log(req.path) next() // calling next middleware function or handler }) app.get('/', (req, res) => { console.log("Route handler called.") res.send("Hello world!") // response sent back – no more middleware called })
about 4 years ago · Juan Pablo Isaza Report

0

Puedes manejar tus errores así:

 res.status(500).send({ msg: 'Wrong email' })

Y puede cambiar el código de estado para enviar diferentes tipos de errores o respuestas:

 res.status(404).send({ msg: 'Not found' }) res.status(200).send({ msg: 'successful' })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!