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[];
};