Skip to content

Commit cc04e7b

Browse files
committed
👍 Add friendlyCall to helper module
1 parent ba82f78 commit cc04e7b

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

denops_std/helper/README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,30 @@ export async function main(denops: Denops): Promise<void> {
2626
}
2727
```
2828

29+
### friendlyCall
30+
31+
Use `friendlyCall()` to call given function and print a friendly error message
32+
(without stack trace) on failure. It's mainly designed for `dispatcher`
33+
functions.
34+
35+
Note that it prints a stack trace when denops is running in debug mode.
36+
37+
```typescript
38+
import { Denops } from "https://deno.land/x/denops_std/mod.ts";
39+
import { friendlyCall } from "https://deno.land/x/denops_std/helper/mod.ts";
40+
41+
export async function main(denops: Denops): Promise<void> {
42+
denops.dispatcher = {
43+
"say": () => {
44+
return friendlyCall(denops, async () => {
45+
// Do whatever you want.
46+
throw new Error("Some error occured");
47+
});
48+
},
49+
};
50+
}
51+
```
52+
2953
### input
3054

3155
Use `input()` which is a wrapper function of `input()` in

denops_std/helper/echo.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,30 @@ export async function echoerr(denops: Denops, message: string): Promise<void> {
3838
});
3939
}
4040

41+
/**
42+
* Call given function and print a friendly error message (without stack trace) on failure.
43+
*
44+
* Print a stack trace when denops is running in debug mode.
45+
*/
46+
export async function friendlyCall(
47+
denops: Denops,
48+
fn: () => Promise<unknown>,
49+
): Promise<unknown> {
50+
if (denops.meta.mode === "debug") {
51+
return await fn();
52+
}
53+
try {
54+
return await fn();
55+
} catch (e: unknown) {
56+
if (e instanceof Error) {
57+
const err: Error = e;
58+
await echoerr(denops, `[${denops.name}]: ${err.message}`);
59+
} else {
60+
throw e;
61+
}
62+
}
63+
}
64+
4165
async function echoVim(denops: Denops, message: string): Promise<void> {
4266
await load(denops, new URL("./echo.vim", import.meta.url));
4367
const waiter = deferred<void>();

0 commit comments

Comments
 (0)