You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EJS中JSON.parse报意外JSON结束错误如何捕获并展示无文档提示

问题原因

报错是因为用户无下发文档时,后端传递给EJS模板的documents变量为空字符串、null或undefined,不属于合法JSON格式,调用JSON.parse时直接触发语法错误。

解决方案1:直接在EJS模板中处理(适合快速修复)

直接在模板中通过try-catch捕获解析错误,解析失败时默认赋值为空数组,再根据数组长度判断渲染内容,替换原代码即可:

<div class="list-group" id="list-tab" role="tablist" style="margin-top: 10px;">
<% 
let docList = []
try {
  // 加兜底逻辑:如果documents是假值直接传入空数组的合法JSON
  docList = JSON.parse(documents || '[]')
} catch (err) {
  // 解析失败时默认是空数组
  docList = []
}

if (docList.length) {
  docList.forEach(document => { 
%>
    <a class="list-group-item list-group-item-action" id="<%= document.Key %>" data-bs-toggle="tab"
      href="#list-<%= document.Key %>" role="tab" aria-controls="list-<%= document.Key %>" style="min-width: 200px;"><%= document.Key %></a>
<% 
  })
} else {
%>
  <p class="text-muted p-3">NO DOCUMENT ISSUED</p>
<% } %>
</div>

解决方案2:后端预处理数据(更规范的工程实现)

推荐把JSON解析逻辑放到后端路由中处理,模板只负责渲染逻辑,代码更易维护。
以Node.js/Express后端为例,渲染页面之前先处理documents参数:

// 渲染dashboard页的路由逻辑
let docList = []
try {
  docList = JSON.parse(用户查询到的documents字段 || '[]')
} catch (err) {
  docList = []
}
// 直接把解析后的数组传给模板
res.render('dashboard', { documents: docList })

此时EJS模板不需要再做解析,代码更简洁:

<div class="list-group" id="list-tab" role="tablist" style="margin-top: 10px;">
<% if (documents.length) {
  documents.forEach(document => { 
%>
    <a class="list-group-item list-group-item-action" id="<%= document.Key %>" data-bs-toggle="tab"
      href="#list-<%= document.Key %>" role="tab" aria-controls="list-<%= document.Key %>" style="min-width: 200px;"><%= document.Key %></a>
<% 
  })
} else {
%>
  <p class="text-muted p-3">NO DOCUMENT ISSUED</p>
<% } %>
</div>

内容的提问来源于stack exchange,提问作者fit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:15:02