在EJS github页面上,只有一个简单的示例:https : //github.com/visionmedia/ejs
例
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
这似乎是在检查是否存在名为user的变量,如果存在,请执行一些操作。h,对不对?
我的问题是,如果用户变量不存在,为什么世界上Node会抛出ReferenceError?这使上面的示例无效。检查变量是否存在的适当方法是什么?我是否应该使用try / catch机制并抓住那个ReferenceError?
ReferenceError: user is not defined
at IncomingMessage.anonymous (eval at <anonymous> (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:140:12))
at IncomingMessage.<anonymous> (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:142:15)
at Object.render (/usr/local/lib/node/.npm/ejs/0.3.1/package/lib/ejs.js:177:13)
at ServerResponse.render (/usr/local/lib/node/.npm/express/1.0.7/package/lib/express/view.js:334:22)
at Object.<anonymous> (/Users/me/Dropbox/Projects/myproject/server.js:188:9)
at param (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:146:21)
at pass (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:162:10)
at /usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:152:27
at Object.restrict (/Users/me/Dropbox/Projects/myproject/server.js:94:5)
at param (/usr/local/lib/node/.npm/connect/0.5.10/package/lib/connect/middleware/router.js:146:21)
我知道我可以通过在服务器代码中简单地添加一个“用户”本地变量来消除此错误,但是这里的全部要点是我想使用您每天的if / else来在运行时检查此类变量是否存在nullcheck类型模式。对于一个不存在的变量,异常对我来说似乎很可笑。