“Manejo de errores en Express” Código de respuesta

Manejo de errores en Express

//app.js
//we need to put this code at last,this code run when there is no route match
app.all('*',(req,res,next)=> {
     const err= new Error(`Can't find ${req.originalUrl} on this server!`)
     err.status=404
     err.statusCode=404
    next(err)
})
//when we use next(err) it will go to error handling middleware and it will catch error and send response.
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
     })
})
Shirshak kandel

ERR MANEJO EXPRESS

app.get('/', function (req, res, next) {
  fs.readFile('/file-does-not-exist', function (err, data) {
    if (err) {
      next(err) // Pass errors to Express.
    } else {
      res.send(data)
    }
  })
})
Enthusiastic Elephant

Respuestas similares a “Manejo de errores en Express”

Preguntas similares a “Manejo de errores en Express”

Más respuestas relacionadas con “Manejo de errores en Express” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código