Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

error handling in 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

error handling in node.js express

1. Operational Errors not bug invalid user input,failed to connect server and database.
2. Programming Errors,bug by the developers like reading properties of undefined,passing a number where object is expected,using await without async.using req.query instead req.body
3. Express use Global error handling Middleware which catch all error. 

//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)
})
Comment

err handling 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)
    }
  })
})
Comment

PREVIOUS NEXT
Code Example
Javascript :: timestamp to date javascript 
Javascript :: docs where field exists 
Javascript :: epoch time js 
Javascript :: onclick on non button 
Javascript :: es6 map usin index 
Javascript :: count number of divs inside a div javascript 
Javascript :: prime number js 
Javascript :: how to use hidden in div in angular 
Javascript :: bootstrap icons react 
Javascript :: two digit js' 
Javascript :: how to turn a number negative in javascript 
Javascript :: inline confirm box javascript 
Javascript :: javascript random integer 
Javascript :: js remove item from array by value 
Javascript :: send mail with javascript 
Javascript :: dom element get attribute 
Javascript :: js function pick properties from object 
Javascript :: convert string into bigNumber in ethers.js 
Javascript :: node mssql 
Javascript :: find longest word in string javascript 
Javascript :: js paste 
Javascript :: disable scroll react 
Javascript :: express return json 
Javascript :: insert variable in string javascript 
Javascript :: split sentence in array js 
Javascript :: how to reload the window by click on button in javascript 
Javascript :: check if an array is empty javascript 
Javascript :: js two array combining with id 
Javascript :: js text word wrap 
Javascript :: jquery checkbox unchecked 
ADD CONTENT
Topic
Content
Source link
Name
3+4 =