Error Handling
try/finally: 成功時も失敗時も後片付けを行う
finally に close を置くことで、処理の成否にかかわらずリソースを解放できます。
SourceresourceUsers.ts
Node.js 22
export interface Resource {
use(): void;
close(): void;
}
export function withResource(resource: Resource): void {
try {
resource.use();
} finally {
resource.close();
}
}TestresourceUsers.test.ts
Node.js 22
import assert from "node:assert/strict";
import test from "node:test";
import { withResource } from "../../src/resources/resourceUsers.js";
test("withResourceは処理後にcloseを必ず呼ぶ", () => {
const events: string[] = [];
withResource({ use: () => events.push("used"), close: () => events.push("closed") });
assert.deepEqual(events, ["used", "closed"]);
});01Assertion
このテストで確認できること
- 使用処理を実行する
- 処理後に close を呼ぶ
Java の try-with-resources の自動 close に相当する所有期間を、TypeScript では try/finally または using 構文で明示します。
OBSERVED RESULT
expected: ["used", "closed"]
actual: ["used", "closed"]