oxc/no-async-endpoint-handlers 可疑
作用
禁止将 async
函数用作 Express 端点处理程序。
这有什么错?
在 v5 之前,Express 不会自动使用应用程序的错误处理程序处理处理程序函数中的 Promise 拒绝。您必须明确地将被拒绝的 promise 传递给 next()
。
js
const app = express();
app.get("/", (req, res, next) => {
new Promise((resolve, reject) => {
return User.findById(req.params.id);
})
.then((user) => res.json(user))
.catch(next);
});
如果不这样做,服务器将因未处理的 Promise 拒绝而崩溃。
js
const app = express();
app.get("/", async (req, res) => {
// Server will crash if User.findById rejects
const user = await User.findById(req.params.id);
res.json(user);
});
有关更多信息,请参阅 Express 的错误处理指南。
范例
此规则针对以下**错误**代码范例
js
const app = express();
app.get("/", async (req, res) => {
const user = await User.findById(req.params.id);
res.json(user);
});
const router = express.Router();
router.use(async (req, res, next) => {
const user = await User.findById(req.params.id);
req.user = user;
next();
});
const createUser = async (req, res) => {
const user = await User.create(req.body);
res.json(user);
};
app.post("/user", createUser);
// Async handlers that are imported will not be detected because each
// file is checked in isolation. This does not trigger the rule, but still
// violates it and _will_ result in server crashes.
const asyncHandler = require("./asyncHandler");
app.get("/async", asyncHandler);
此规则针对以下**正确**代码范例
js
const app = express();
// not async
app.use((req, res, next) => {
req.receivedAt = Date.now();
});
app.get("/", (req, res, next) => {
fs.readFile("/file-does-not-exist", (err, data) => {
if (err) {
next(err); // Pass errors to Express.
} else {
res.send(data);
}
});
});
const asyncHandler = async (req, res) => {
const user = await User.findById(req.params.id);
res.json(user);
};
app.get("/user", (req, res, next) => asyncHandler(req, res).catch(next));
配置
此规则采取以下配置
ts
type NoAsyncEndpointHandlersConfig = {
/**
* An array of names that are allowed to be async.
*/
allowedNames?: string[];
};