提问人:dfcb 提问时间:11/16/2023 最后编辑:dfcb 更新时间:11/16/2023 访问量:70
为什么“尝试......Catch“块没有捕获错误?
Why "Try...Catch" block does not catch the errors?
问:
我希望我的程序发送以下代码中 catch 块中指定的错误,并将其显示在 Bootstrap 模式最新版本的 EJS 文件中。
我的索引.js文件中的代码如下
import express from "express";
import bodyParser from "body-parser";
import pg from "pg";
const app = express();
const port = 3000;
const db = new pg.Client({
user: 'postgres',
host: 'localhost',
database: 'World',
password: 'something',
port: 5432,
});
db.connect();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
async function alreadyVisited() {
const result = await db.query("SELECT country_code FROM visited_countries");
let countriesVisited = [];
result.rows.forEach((country) => {
countriesVisited.push(country.country_code);
});
return countriesVisited;
}
let totalOfCountries = 0;
app.get("/", async (req, res) => {
const countriesVisited = await alreadyVisited();
totalOfCountries = countriesVisited.length;
res.render('index.ejs', { countries: countriesVisited, total: totalOfCountries });
});
app.post('/add', async (req, res) => {
const countryChosen = req.body["country"];
console.log(countryChosen);
try {
const result = await db.query(
"SELECT country_code FROM countries WHERE country_name = $1",
[countryChosen]
);
const data = result.rows[0];
console.log(data);
const countryCode = data.country_code;
console.log(countryCode);
try {
await db.query(
"INSERT INTO visited_countries (country_code) VALUES ($1)",
[countryCode]
);
res.redirect("/");
} catch (err) {
console.log(err);
const countriesVisited = await alreadyVisited();
res.render('index.ejs', {
countries: countriesVisited,
total: countriesVisited.length,
error: "Country has already been added, try again.",
});
}
} catch (err) {
console.log(err);
const countriesVisited = await alreadyVisited();
res.render('index.ejs', {
countries: countriesVisited,
total: countriesVisited.length,
error: `That country does not exist, try again.`,
});
}
});
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
});
这是我的index.ejs文件的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Travel Tracker</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<link rel="stylesheet" href="./styles/main.css">
</head>
<body>
<!-- Modal -->
<% if (locals.error) { %>
<div class="modal fade" id="errorModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="staticBackdropLabel">⚠️ Wait a moment... ⚠️</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<%= error %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
<script>
$('#errorModal').modal("show");
</script>
<% } %>
<form action="/add" method="post">
<input type="text" name="country" autofocus placeholder="Enter country name">
<button type="submit" id="submitForm">Add</button>
</form>
<h2 class="total-count">Total of Countries: <%=total%>
</h2>
<!-- JQuery and bootstrap CDN -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
<script>
const country_codes = "<%= countries %>".split(",")
console.log(typeof ("<%= countries %>"))
country_codes.forEach(code => {
$(`#${code}`).css('fill', 'teal');
// document.getElementById(code).style.fill = 'teal'
});
</script>
</body>
</html>
当我尝试输入一个不存在的国家/地区时,终端中会出现一个错误,但此错误不会传递到位于 index.ejs 中的模态。
当我输入不存在的国家/地区名称时,终端中出现的错误: TypeError:无法读取未定义的属性(读取“country_code”)
当我尝试插入“visited_countries”表中已存在的国家/地区时,会出现此错误,并且是正确的,因为它已在表中注册: 错误:重复的键值违反了唯一约束“visited_countries_country_code_key”
catch 块似乎无法有效地捕获错误。 顺便说一句,在每种情况下,我都尝试呈现自定义错误消息,将其发送到“res.render”,但没有成功。 我感谢这方面的任何帮助。谢谢。
答: 暂无答案
评论
const countryCode = data.country_code;