简体   繁体   English

如何实现 ExpressJS 错误处理,以便针对不同的 HTTP 状态码显示不同的错误

[英]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./error路径上创建一个错误并将其传递给下一个 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整个代码位于: https://github.com/iamdakshak/react-training-work/blob/master/Node%20Assignments/Assignment%203%20-%20Sever%20basics%2C%20Middlewares%2C%20HTTP% 20方法/index.js

How can it be implemented?如何实施?

There is no status() method on the request object in Express. Express 中的请求 object 上没有status()方法。

The status code is stored in the response object, to check it:状态码存储在响应 object 中,检查它:

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

To set the status code use:要设置状态码,请使用:

res.status(500)

You could use an object with messages您可以使用带有消息的 object

 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"); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM