Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

global error handling middleware 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
     })
})
Comment

express error middleware

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

PREVIOUS NEXT
Code Example
Javascript :: select all checkbox jquery 
Javascript :: mongoose query if field exists where filed exists 
Javascript :: how to create a random number generator in javascript 
Javascript :: “javascript remove last element from array 
Javascript :: joi string custom validation fuction 
Javascript :: convert json to dataframe python 
Javascript :: bootstrap switch on change 
Javascript :: javascript backslash 
Javascript :: jquery animation 
Javascript :: iseet jquery 
Javascript :: simple reactjs login form 
Javascript :: jquery siblings 
Javascript :: read a file nodejs 
Javascript :: Cast to ObjectId failed for value 
Javascript :: js refresh iframe 
Javascript :: javascript element read attribute 
Javascript :: how to print in jsp 
Javascript :: html button javascript void 
Javascript :: delete multiple keys from object javascript 
Javascript :: javascript return longest string in array 
Javascript :: vue watch child property 
Javascript :: get first day of the week of a given date javascript js 
Javascript :: prettier/prettier in react 
Javascript :: regex to match string not in between quotes 
Javascript :: nodejs current timestamp 
Javascript :: get year from date javascript 
Javascript :: REACT-ICONS reduce thickness 
Javascript :: .ignore file nodejs 
Javascript :: generate random id javascript 
Javascript :: local storage ha 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =