Skip to content

Commit 71fc6cc

Browse files
committed
(test): add tests for async/await try-catch-finally re-throw cases
1 parent 4b3162b commit 71fc6cc

1 file changed

Lines changed: 98 additions & 0 deletions

File tree

test/unit/builtins/async-await.spec.ts

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,104 @@ describe("try/catch in async function", () => {
11261126
.setTsHeader(promiseTestLib)
11271127
.expectToEqual(["finally", "ok"]);
11281128
});
1129+
1130+
test.each([0, 1, 2])("async re-throw (%p)", i => {
1131+
util.testModule`
1132+
const i: number = ${i};
1133+
async function foo() {
1134+
try {
1135+
try {
1136+
if (i === 0) { throw "z"; }
1137+
} catch (e) {
1138+
throw "a";
1139+
} finally {
1140+
if (i === 1) { throw "b"; }
1141+
}
1142+
} catch (e) {
1143+
throw (e as string).toUpperCase();
1144+
} finally {
1145+
throw "C";
1146+
}
1147+
}
1148+
export let result: string = "x";
1149+
async function run() {
1150+
try {
1151+
await foo();
1152+
} catch (e) {
1153+
result = (e as string)[(e as string).length - 1];
1154+
}
1155+
}
1156+
run();
1157+
`.expectToEqual({ result: "C" });
1158+
});
1159+
1160+
test("async: catch re-throws, finally still runs", () => {
1161+
util.testModule`
1162+
const foo = async () => {
1163+
throw "original";
1164+
};
1165+
1166+
let finallyCalled = false;
1167+
let caughtError: any = false;
1168+
1169+
const run = async () => {
1170+
try {
1171+
await foo();
1172+
} catch (e) {
1173+
throw "re-thrown: " + e;
1174+
} finally {
1175+
finallyCalled = true;
1176+
}
1177+
};
1178+
1179+
run().catch(e => { caughtError = e; });
1180+
1181+
export const result = { finallyCalled, caughtError };
1182+
`.expectToEqual({
1183+
result: {
1184+
finallyCalled: true,
1185+
caughtError: "re-thrown: original",
1186+
},
1187+
});
1188+
});
1189+
1190+
test("async: finally throw overrides catch throw", () => {
1191+
util.testModule`
1192+
const run = async () => {
1193+
try {
1194+
throw "try-error";
1195+
} catch (e) {
1196+
throw "catch-error";
1197+
} finally {
1198+
throw "finally-error";
1199+
}
1200+
};
1201+
1202+
let caughtError: any = false;
1203+
run().catch(e => { caughtError = e; });
1204+
1205+
export const result = caughtError;
1206+
`.expectToEqual({ result: "finally-error" });
1207+
});
1208+
1209+
test("async: finally return overrides catch throw", () => {
1210+
util.testFunction`
1211+
async function run() {
1212+
try {
1213+
throw "try-error";
1214+
} catch (e) {
1215+
throw "catch-error";
1216+
} finally {
1217+
return "finally-return";
1218+
}
1219+
}
1220+
1221+
let result: any;
1222+
run().then(v => { result = v; }).catch(e => { result = "rejected: " + e; });
1223+
1224+
return result;
1225+
`.expectToEqual("finally-return");
1226+
});
11291227
});
11301228

11311229
describe("async generators are unsupported", () => {

0 commit comments

Comments
 (0)