为什么我的req.flash不起作用?

时间:2011-03-29 00:09:08

标签: json parsing node.js exception-handling try-catch

这是一个Node.js函数。它的工作原理是,错误的JSON数据被踢出,但它也会闪现失败的消息。为什么呢?

// Create document 
app.post('/documents.:format?', loadUser, function(req, res) {

        /////////////////////////added by adam
        //tests to see if the inputed text is valid JSON data
        data = req.body.d.data;
        console.log("///////////" + data);

        try { 
            type = JSON.parse(data);
            console.log(type);
        } catch (ex) { 
            console.log("bad json: "+data);
            req.flash('Nope', 'Invalid JSON');
            res.redirect('/documents');
            return;
        }

            var d = new Document(req.body.d);
            d.user_id = req.currentUser.id;
            d.save(function() {
                switch (req.params.format) {
                    case 'json':
                        res.send(d.toObject());
                        break;

                    default:
                        req.flash('info', 'Document created');
                        res.redirect('/documents');
                }
            }); 

1 个答案:

答案 0 :(得分:0)

catch块包含错误消息和“坏JSON”记录器,因此由于块范围,它们将始终同时出现。

相关问题