JavaScript非真实错误类异常的正确返回类型及实现咨询
Nice question! Let's break down how to properly define the return type for this function—this is a super common scenario when combining database operations, error handling, and integrity checks, so it's worth getting right.
Core Observations
First, let's clarify your function's behavior to ground the type definition:
- Success path: Returns the
_idof the inserted MongoDB document (either astringor MongoDB's nativeObjectIdtype, depending on your database setup). - Failure paths: Never returns a value—instead, it throws an error (either the original MongoDB insertion error, or your custom "未插入任何文档" error).
Since exceptions terminate the function's execution entirely, we only need to define the return type for the successful case. The error scenarios are handled via throw, not via return values.
Type Definition Examples
TypeScript
If you're using TypeScript, you can explicitly define the return type to match the actual _id type your database returns. Most MongoDB drivers export an ObjectId type, so you can use that directly for strict type safety:
import { ObjectId, InsertOneResult } from "mongodb"; async function persistState(state: Record<string, unknown>): Promise<ObjectId> { // Generate SHA256 hash for integrity and duplicate checks const stateString = JSON.stringify(state); const hash = generateSHA256(stateString); // Assume this is your existing hash function // Check for duplicate records first const existingDoc = await db.collection("stateStore").findOne({ hash }); if (existingDoc) { throw new Error("Duplicate record detected"); } // Attempt to insert the state document const insertResult: InsertOneResult = await db.collection("stateStore").insertOne({ state: stateString, hash, createdAt: new Date(), }); if (insertResult.insertedId) { return insertResult.insertedId; } else { throw new Error("未插入任何文档"); } }
If your database uses string-based _ids instead of ObjectId, simply replace ObjectId with string in the return type.
JavaScript with JSDoc
If you're writing vanilla JavaScript but want type hints for tools like VS Code, use JSDoc to document the return type and possible error scenarios clearly:
/** * Persists a state object to MongoDB with SHA256 integrity and duplicate checks * @param {Record<string, unknown>} state - The state object to persist * @returns {Promise<string|import("mongodb").ObjectId>} The _id of the successfully inserted document * @throws {Error} Throws original MongoDB errors, duplicate record errors, or "未插入任何文档" error on insertion failure */ async function persistState(state) { // Same logic as the TypeScript example above }
Key Notes
- Don't include error cases in the return type: Since your function throws errors instead of returning failure values, the return type only needs to represent the successful outcome. Callers are expected to handle errors with
try/catchblocks. - Be specific with types: Using MongoDB's native
ObjectIdtype (instead of a genericstring) adds type safety and makes your code's intent clearer to other developers. - Document exceptions explicitly: Whether using TypeScript or JSDoc, make sure to note all possible error scenarios so callers know what to catch and handle.
内容的提问来源于stack exchange,提问作者Jankapunkt

