Table of Contents
npm install try-asAdd the transform to your asc build and load it last.
asc assembly/index.ts --transform try-as/transformOr in asconfig.json:
{
"options": {
"transform": ["try-as/transform"]
}
}If you use multiple transforms, keep try-as/transform last.
try-as rewrites try/catch/finally, throw, abort, and selected stdlib throw paths so they can be handled through a consistent Exception object.
import { Exception } from "try-as";
try {
throw new Error("boom");
} catch (e) {
const err = e as Exception;
console.log(err.toString()); // Error: boom
} finally {
console.log("done");
}import { Exception, ExceptionType } from "try-as";Exception.type: ExceptionTypeException.toString(): stringException.is<T>(): boolException.as<T>(): TException.clone(): ExceptionException.rethrow(): void
ExceptionType:
NoneAbortThrowUnreachable
import { Exception, ExceptionType } from "try-as";
try {
abort("fatal");
} catch (e) {
const err = e as Exception;
if (err.type == ExceptionType.Abort) {
console.log(err.toString()); // abort: fatal
}
}import { Exception } from "try-as";
class MyError extends Error {
constructor(message: string) {
super(message);
}
}
try {
throw new MyError("typed");
} catch (e) {
const err = e as Exception;
if (err.is<MyError>()) {
const typed = err.as<MyError>();
console.log(typed.message);
}
}import { Exception } from "try-as";
try {
// risky code
} catch (e) {
const err = e as Exception;
if (!err.is<Error>()) {
err.rethrow();
}
}Stdlib exceptions such as missing map keys, empty array pops, out-of-range string access, and malformed URI decode errors are catchable.
import { Exception } from "try-as";
try {
new Map<string, string>().get("missing");
} catch (e) {
const err = e as Exception;
console.log(err.toString()); // Error: Key does not exist
}- Runtime/internal trap paths are intentionally not rewritten.
- Exceptions from these internals are not catchable by
try-as:~lib/rt~lib/shared~lib/wasi_~lib/performance
- This library handles transformed throw/abort flows, not low-level Wasm traps like out-of-bounds memory faults.
DEBUG=1enables transform diagnostics.WRITE=pathA,pathBwrites transformed source snapshots as*.tmp.ts.
Example:
DEBUG=1 WRITE=./assembly/test.ts,~lib/map asc assembly/test.ts --transform try-as/transformnpm run build:transform
npm test
npm run formatThis project is distributed under the MIT license.
- Issues: https://github.com/JairusSW/try-as/issues
- Repository: https://github.com/JairusSW/try-as
- Email: [email protected]
- Website: https://jairus.dev