Dakshak
Dakshak

Reputation: 29

How to implement ExpressJS Error Handling so that it shows different errors for different HTTP Status codes

I wanna implement this task and I'm unable to understand how to do it.

Create an error on /error path and pass it to the next function. Depending on the type of error message you are showing, use proper error status codes to show the error.

I tried to use this logic but it doesn't work.

app.use((req, res, next) => {
  if (req.status(403)) {
    res.send("<h1>ERROR FOUND</h1>");
    next();
  } else if (req.status(404)) {
    res.send("<h1>PAGE NOT FOUND</h1>");
    next();
  } else if (req.status(500)) {
    res.send("<h1>INTERNAL SERVER ERROR</h1>");
    next();
  } else if (req.status(200)) {
    res.send("<h1>COnnected!</h1>");
    next();
  } else console.log("No error");
});

The whole code is available at: https://github.com/iamdakshak/react-training-work/blob/master/Node%20Assignments/Assignment%203%20-%20Sever%20basics%2C%20Middlewares%2C%20HTTP%20methods/index.js

How can it be implemented?

Upvotes: 0

Views: 172

Answers (2)

Zerowiel
Zerowiel

Reputation: 170

You could use an object with messages

const messages = {
  403: "<h1>ERROR FOUND</h1>",
  404: "<h1>PAGE NOT FOUND</h1>",
  500: "<h1>INTERNAL SERVER ERROR</h1>",
  200: "<h1>COnnected!</h1>",
}

const req = {statusCode: "200"}

if(messages[req.statusCode]){
  console.log(messages[req.statusCode]);
  // res.send(messages[req.statusCode])
} else {
  console.log("No error");
}

Upvotes: 1

Two Horses
Two Horses

Reputation: 1692

There is no status() method on the request object in Express.

The status code is stored in the response object, to check it:

if (res.statusCode === 500)
  next()

To set the status code use:

res.status(500)

Upvotes: 1

Related Questions