NodeJs HTTP状态异常处理 [英] NodeJs http status exception handling

查看:870
本文介绍了NodeJs HTTP状态异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了nodejs + express应用程序。现在在我的应用程序中,当捕获到异常的错误按以下方式发送

I have created nodejs + express application. Now in my application when exception caught errors are send as follows

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('不提供访问令牌' ); 我可以发送类似这样的信息

Instead of sending res.status(403).send('Access token not provided'); can I send something like this

exception.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
});

而且我怎么能一次捕获所有异常?

And also how can I caught all exceptions in once place ?

推荐答案

您可以使用类似这样的东西:

You could use something like this:

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 错误处理中间件,它将检查抛出的错误是否是 httpError 的实例(是您要创建的所有HTTP错误类的超类),如果是,则将根据代码和消息生成特定的响应(否则将生成通用的500错误响应)。

This uses an Express error handling middleware that will check if the error that got thrown is an instance of httpError (which would be the superclass of all the HTTP error classes that you'd want to create) and, if so, would generate a particular response according to the code and the message (or generate a generic 500 error response otherwise).

这篇关于NodeJs HTTP状态异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆