node.js - NodeJs http状态异常处理

标签 node.js express exception

我创建了nodejs + Express应用程序。现在在我的应用程序中,当异常捕获错误时发送如下

app.get('/data', (req, res) => {
      if(!req.params.token){
        return res.status(403).send('Access token not provided');
      }

      //do something here
    });

我可以发送这样的内容,而不是发送res.status(403).send('Access token notprovided');

异常.js

class Forbidden {
    constructor(message,stack = null){
        this.code = 403;
        this.message = message
        this.stack = stack;
    }
}

app.js

var httpForbidden = require('exception.js');

app.get('/data', (req, res) => {
if(!req.params.token){
    return new httpForbidden ('Access token not provided');
}

//do something here
});

我怎样才能在一个地方捕获所有异常?

最佳答案

你可以使用这样的东西:

class httpError {}

class httpForbidden extends httpError {
  constructor(message, stack = null) {
    super();
    this.code = 403;
    this.message = message
    this.stack = stack;
  }
}

app.get('/', (req, res) => {
  if (!req.params.token) {
    throw new httpForbidden('Access token not provided');
  }
  ...
});

app.use((err, req, res, next) => {
  if (err instanceof httpError) {
    return res.status(err.code).send(err.message);
  }
  res.sendStatus(500);
});

这使用 Express error handling middleware它将检查抛出的错误是否是 httpError 的实例(这将是您想要创建的所有 HTTP 错误类的父类(super class)),如果是,将生成一个特定的根据代码和消息进行响应(否则生成通用 500 错误响应)。

关于node.js - NodeJs http状态异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42280569/

相关文章:

mysql - 如何用 NodeJS 处理这些 MySQL 情况

javascript - 在 Express.js 中外部化 route.param() 调用

node.js - 在 mongoose.js 上保存钩子(Hook)之前使用的正确方法

PHP:像 Xdebug 一样打印捕获异常

sql-server - 请求错误 : { message: 'Requests can only be made in the LoggedIn state, not the SentLogin7WithStandardLogin state' , 代码: 'EINVALIDSTATE' }

javascript - 如何将 webpack 应用部署到 heroku

java - Eclipse 插件 : java. lang.NoClassDefFoundError

c++ - 如何检查输出流是否为 C++ 中的 std::cout?

node.js - 如何在nest.js 中为socket.io 创建SSL 连接?

javascript - express .js : stream result from Mongo and serialize non-blockingly