【问题标题】:Try catch block in express [duplicate]尝试在快递中捕获块[重复]
【发布时间】:2020-01-27 23:54:48
【问题描述】:

我在谷歌上搜索并找到了一些示例(如this)。

我在那里做了所有的事情,一切都很好!

但现在我的每个路由器函数都包含 try...catch 块。像这样:

accounts = express.Router()

accounts.post('/following', async (req, res, next) => {
    try {
        ***do some stuff***
        if (smth_bad)
            next(new ErrorHandler(413, 400, "Wrong data"));

    } catch (e) {
        next(e)
    }
});

accounts.post('/followers', async (req, res, next) => {
    try {
        ***do some stuff***
        if (smth_bad)
            next(new ErrorHandler(413, 400, "Wrong data"));
    } catch (e) {
        next(e)
    }
});


accounts.post('/posts', async (req, res, next) => {
    try {
        ***do some stuff***
        if (smth_bad)
            next(new ErrorHandler(413, 400, "Wrong data"));
    } catch (e) {
        next(e)
    }
});

accounts.post('/pizza', async (req, res, next) => {
    try {
        ***do some stuff***
        if (smth_bad)
            next(new ErrorHandler(413, 400, "Wrong data"));
    } catch (e) {
        next(e)
    }
});

app.use('/api/v1/account', accounts);

app.use((err, req, res, next) => {
    handleError(err, res);
});

我知道,我可以在没有 try...catch 的情况下使用 next(),但我想处理意外错误并将其告诉用户。我的处理方式如下:

class ErrorHandler extends Error {
    constructor(statusCode, httpStatus, message) {
        super();
        this.statusCode = statusCode;
        this.httpStatus = httpStatus;
        this.message = message;
    }
}

const handleError = (err, res) => {
    if(err instanceof ErrorHandler){
        const { statusCode, message, httpStatus } = err;
        res.status(httpStatus).json({
            status: "error",
            statusCode,
            message
        });
    } else {
        console.error(err);
        res.status(500).json({
            status: "error",
            statusCode: '510',
            message: 'Server error',
        });
    }

};

有没有办法简化每个路由器中的 try...catch 块?

【问题讨论】:

标签: javascript node.js express try-catch


【解决方案1】:

首先,try/catch 不会异步捕获错误。如果您在 try/catch 中的所有代码都是同步的,那么您正在做的事情将起作用,但正如您已经发现的那样,这是解决问题的一种非常麻烦的方法。

有很多方法可以解决这个问题,但我认为也许你应该问一个不同的问题:“好的模块化代码是什么样的?”或“如何在我的代码中实现路由器?”

我建议你去寻找有关如何构建路由器的模式。

一种可能的方法是编写您在 try/catch 块之外定义的函数(为了整洁,可能在另一个模块中)并在 try/catch 中使用它们。像这样:

const getStuffFunction = function(req,callback){
  //do stuff here
}

accounts.post('/pizza', async (req, res, next) => {
  getStuffFunction(req,function(){
    //do router stuff here after your business logic is done
  })

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2011-08-23
    • 2021-08-27
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多