“Express Erro Middleware” Respostas de código

Express Erro Middleware

function errorHandler (err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  res.status(500)
  res.render('error', { error: err })
}
abhishekdipu

Middleware de manuseio de erros global 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

manuseio de erro de gerador expresso

app.get('/', function (req, res) {
  throw new Error('BROKEN') // Express will catch this on its own.
})
Strange Shrew

Respostas semelhantes a “Express Erro Middleware”

Perguntas semelhantes a “Express Erro Middleware”

Mais respostas relacionadas para “Express Erro Middleware” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código