简体   繁体   English

Node.js Express-根据错误类型不同地处理错误

[英]Node.js Express - Handle Error Differently Based on Error Type

A few details... I'm using Express 4, Node 0.12.2 and Express-Handlebars as my view engine. 一些细节...我正在使用Express 4,Node 0.12.2和Express-Handlebars作为我的视图引擎。

I'm trying to render a partial via AJAX call and would like to handle different errors types differently. 我正在尝试通过AJAX调用呈现部分内容,并希望以不同的方式处理不同的错误类型。 The err object passed on the callback invocation doesn't seem to have much useful info to work with, just an error message. 在回调调用中传递的err对象似乎并没有太多有用的信息,只是一条错误消息。 Is there something I'm missing here? 我在这里想念什么吗?

// Search (Partial)
router.get('/search-products', function (req, res, next) {
    res.render('partials/search/products', {layout: 'ajax'}, function(err, html){
        if(err) {
            // return res.status(404).send(err);
            // return res.status(500).send(err);
        }
        res.send(html);
    });
});

That error object isn't going to have a status code because it's an error object generated by the view engine. 该错误对象将没有状态代码,因为它是视图引擎生成的错误对象。 If that error is populated you can pretty much assume it's a 500 error because the view engine failed to compile a view for some reason. 如果该错误被填充,您几乎可以认为是500错误,因为视图引擎由于某种原因未能编译视图。

For example, if you're using Jade, that error object will be populated if you try to have Jade compile a template that has invalid Jade syntax. 例如,如果您使用的是Jade,则当您尝试让Jade编译具有无效Jade语法的模板时,将填充该错误对象。 The error there is never going to be HTTP related which means it's always just a server-side error and status code 500 should suffice. 该错误永远不会与HTTP相关,这意味着它始终只是服务器端错误,状态码500应该足够。

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

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