@stateward/plugin-errors 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/catch-hides-unexpected.d.ts +4 -1
- package/dist/catch-hides-unexpected.js +87 -11
- package/dist/catch-misses-error.d.ts +1 -1
- package/dist/catch-misses-error.js +63 -20
- package/dist/finally-can-throw.js +46 -6
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/inference/analysis.d.ts +109 -0
- package/dist/inference/analysis.js +170 -0
- package/dist/inference/builtins.d.ts +7 -2
- package/dist/inference/builtins.js +20 -33
- package/dist/inference/deps.js +2 -2
- package/dist/inference/needs.d.ts +16 -0
- package/dist/inference/needs.js +27 -0
- package/dist/inference/packages.d.ts +24 -32
- package/dist/inference/packages.js +156 -675
- package/dist/inference/project.d.ts +2 -2
- package/dist/inference/project.js +3 -2
- package/dist/inference/solve.d.ts +29 -4
- package/dist/inference/solve.js +34 -5
- package/dist/inference/summarize.d.ts +28 -15
- package/dist/inference/summarize.js +339 -135
- package/dist/inference/summary.d.ts +46 -5
- package/dist/inference/summary.js +89 -13
- package/dist/inference/unreachable.d.ts +5 -0
- package/dist/inference/unreachable.js +160 -0
- package/dist/must-handle-error.d.ts +2 -1
- package/dist/must-handle-error.js +4 -4
- package/dist/narrow-try.d.ts +2 -0
- package/dist/narrow-try.js +62 -7
- package/dist/plugin.d.ts +12 -2
- package/dist/plugin.js +4 -2
- package/dist/react/fallbacks.js +35 -14
- package/dist/react/tree.d.ts +10 -0
- package/dist/react/tree.js +54 -7
- package/dist/refactors.js +35 -2
- package/dist/render-throw-without-boundary.d.ts +13 -4
- package/dist/render-throw-without-boundary.js +100 -10
- package/dist/result-ignored.d.ts +4 -1
- package/dist/result-ignored.js +51 -10
- package/dist/result-type.d.ts +2 -0
- package/dist/result-type.js +8 -2
- package/dist/result-unchecked.d.ts +4 -1
- package/dist/result-unchecked.js +320 -96
- package/dist/rules.meta.d.ts +29 -14
- package/dist/rules.meta.js +19 -14
- package/dist/syntax.d.ts +0 -13
- package/dist/syntax.js +0 -79
- package/dist/text.d.ts +15 -2
- package/dist/text.js +28 -5
- package/dist/throws-doc-mismatch.d.ts +1 -1
- package/dist/throws-doc-mismatch.js +59 -5
- package/dist/throws-reads.d.ts +3 -0
- package/dist/throws-reads.js +108 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -42,10 +42,11 @@ rules: {
|
|
|
42
42
|
Add-on rules stay off until you list their add-on:
|
|
43
43
|
|
|
44
44
|
```ts
|
|
45
|
-
addons: ["errors/
|
|
45
|
+
addons: ["errors/catch-hides-unexpected", "errors/result-unchecked"],
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
-
- `errors/
|
|
48
|
+
- `errors/catch-hides-unexpected`: `catch-hides-unexpected`
|
|
49
|
+
- `errors/result-unchecked`: `result-unchecked`
|
|
49
50
|
|
|
50
51
|
Every key of the config: [config.md](https://github.com/khoing1111/ts-stateward/blob/main/docs/user/config.md).
|
|
51
52
|
|
|
@@ -55,22 +56,22 @@ Every key of the config: [config.md](https://github.com/khoing1111/ts-stateward/
|
|
|
55
56
|
|
|
56
57
|
## Rules
|
|
57
58
|
|
|
58
|
-
| Rule | What it finds |
|
|
59
|
+
| Rule | What it finds | Details | Kind | `recommended` | `strict` |
|
|
59
60
|
| --- | --- | --- | --- | --- | --- |
|
|
60
61
|
| [must-handle-error](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/must-handle-error.md) | a call that can throw an error marked `@mustHandle`, with no code that handles or passes it on | An error marked `@mustHandle` needs a decision at each call, such as a message to the user; a call that neither catches it nor passes it on lets it reach the top. | Core | error | error |
|
|
61
62
|
| [result-ignored](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-ignored.md) | a `Result` dropped as a statement, after `void` or after `await` | A `Result` dropped as a statement discards its error, so a failed call looks the same as a successful one. | Core | error | error |
|
|
62
|
-
| [result-unchecked](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-unchecked.md) | a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked (guess) | A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked. | Core | warning | warning |
|
|
63
63
|
| [throws-doc-mismatch](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/throws-doc-mismatch.md) | a `@throws` tag that lists an error the function cannot throw, or misses one it can | Callers decide what to catch from `@throws`: a class it omits reaches them unhandled, and a class listed in excess asks them to handle a case that cannot happen. | Core | error | error |
|
|
64
|
-
| [
|
|
64
|
+
| [result-unchecked](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-unchecked.md) | a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked (heuristic) | A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked. | Add-on `result-unchecked` | warning | warning |
|
|
65
65
|
| [catch-misses-error](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/catch-misses-error.md) | a `catch` that branches on error classes but misses one its `try` can throw | An error class the `try` can throw and the `catch` does not test goes to the generic branch, or is ignored; a branch for it, or a rethrow, handles it explicitly. | Core | error | error |
|
|
66
66
|
| [finally-can-throw](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/finally-can-throw.md) | a `finally` that calls something that can throw and replace the original error | An error thrown in `finally` replaces the error that was already thrown, so the report names the cleanup instead of the original cause. | Core | error | error |
|
|
67
|
-
| [
|
|
67
|
+
| [catch-hides-unexpected](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/catch-hides-unexpected.md) | a `catch` that handles some error classes with `instanceof` and ignores the rest | A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible. | Add-on `catch-hides-unexpected` | error | error |
|
|
68
68
|
| [render-throw-without-boundary](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/render-throw-without-boundary.md) | a component that can throw a known error while rendering, with no error boundary above it | An error thrown while rendering, with no error boundary above the component, unmounts the whole React tree and leaves a blank page. | Core | warning | warning |
|
|
69
69
|
|
|
70
70
|
**Core** rules are on in every preset. **Coverage** rules point at code whose types do not say
|
|
71
71
|
enough for stateward to check it; they are info under `recommended` and errors under `strict`.
|
|
72
|
-
**
|
|
73
|
-
|
|
72
|
+
**Convention** rules check a team convention, not a fact about the code: they stay off until the
|
|
73
|
+
config sets `conventions: true` or names the rule under `rules`; a convention rule that reads only what the project states is on, and silent until the project states something. **Add-on** rules stay off until
|
|
74
|
+
you list their add-on in `addons`. The table shows the severity of both once they are on. A rule marked (heuristic) judges from patterns in the code, not only from types, so
|
|
74
75
|
it can be wrong and is never an error unless you make it one.
|
|
75
76
|
|
|
76
77
|
Each rule's page shows an example with what stateward prints for it, the fix, why it matters, what it misses, and its options. The pack's page: [docs/packs/errors.md](https://github.com/khoing1111/ts-stateward/blob/main/docs/packs/errors.md). Every pack's rules: [the rules index](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/README.md).
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
2
2
|
export declare const GROUP = "catch";
|
|
3
3
|
export declare const catchHidesUnexpected: import("@stateward/core").FileRule<{
|
|
4
|
-
restUsesError: import("@stateward/core").BooleanOption
|
|
4
|
+
restUsesError: import("@stateward/core").BooleanOption & Pick<{
|
|
5
|
+
readonly default: false;
|
|
6
|
+
readonly description: "The branch for the other errors must use the error (rethrow it, wrap it, report it); a generic message alone does not count.";
|
|
7
|
+
}, "internal">;
|
|
5
8
|
}, "catch">;
|
|
6
9
|
//# sourceMappingURL=catch-hides-unexpected.d.ts.map
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
|
-
import { defineRule, option } from "@stateward/core";
|
|
2
|
+
import { codeOnOneLine, defineRule, option, offByDefaultText, } from "@stateward/core";
|
|
3
3
|
import { stripParentheses } from "./syntax.js";
|
|
4
|
-
import { codeList, fitted,
|
|
4
|
+
import { codeList, fitted, withExample } from "./text.js";
|
|
5
5
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
6
6
|
export const GROUP = "catch";
|
|
7
|
+
/** Off by default since 1.3: 4 of 7 of its findings checked on real projects were right. */
|
|
8
|
+
const OFF_BY_DEFAULT = { since: "1.3", right: 4, checked: 7 };
|
|
7
9
|
const EXPLAIN = `# errors/catch-hides-unexpected
|
|
8
10
|
|
|
9
11
|
A \`catch\` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.
|
|
@@ -50,7 +52,7 @@ export async function submit(order: string, show: (text: string) => void): Promi
|
|
|
50
52
|
}
|
|
51
53
|
\`\`\`
|
|
52
54
|
|
|
53
|
-
A quick fix adds \`else { throw e; }\` to an \`if\` chain. For a \`switch (true)\`, add \`default: throw e;\` yourself; the message shows it. Wrapping the error with \`{ cause: e }\`, or any statement after the chain, counts too, since it runs for every error.
|
|
55
|
+
A quick fix adds \`else { throw e; }\` to an \`if\` chain. The message offers three readings: rethrow, handle the rest in the last branch, or, when dropping them is on purpose, an \`else\` (or \`default:\`) with a comment that says why: a branch with only a comment is taken as the drop, stated, and reported no more. For a \`switch (true)\`, add \`default: throw e;\` yourself; the message shows it. Wrapping the error with \`{ cause: e }\`, or any statement after the chain, counts too, since it runs for every error.
|
|
54
56
|
|
|
55
57
|
## Why it matters
|
|
56
58
|
|
|
@@ -64,8 +66,11 @@ A \`catch\` that handles \`NotFoundError\` and \`AuthError\` and has no last bra
|
|
|
64
66
|
|
|
65
67
|
## Turn it on or off
|
|
66
68
|
|
|
69
|
+
${offByDefaultText(OFF_BY_DEFAULT)}
|
|
70
|
+
|
|
67
71
|
\`\`\`ts
|
|
68
|
-
|
|
72
|
+
addons: ["errors/catch-hides-unexpected"]
|
|
73
|
+
rules: { "errors/catch-hides-unexpected": "warning" } // on, as a warning
|
|
69
74
|
rules: { "errors/catch-hides-unexpected": ["error", { restUsesError: true }] } // the last branch must use the error
|
|
70
75
|
\`\`\`
|
|
71
76
|
`;
|
|
@@ -91,7 +96,7 @@ function instanceOfClasses(condition, variable, sourceFile) {
|
|
|
91
96
|
if (operator === ts.SyntaxKind.InstanceOfKeyword) {
|
|
92
97
|
const subject = stripParentheses(node.left);
|
|
93
98
|
return ts.isIdentifier(subject) && subject.text === variable
|
|
94
|
-
? [
|
|
99
|
+
? [codeOnOneLine(stripParentheses(node.right).getText(sourceFile))]
|
|
95
100
|
: [];
|
|
96
101
|
}
|
|
97
102
|
if (operator === ts.SyntaxKind.BarBarToken ||
|
|
@@ -123,6 +128,11 @@ function dispatchOf(statement, variable, sourceFile) {
|
|
|
123
128
|
start: statement,
|
|
124
129
|
classes,
|
|
125
130
|
rest: realStatements(end.elseStatement),
|
|
131
|
+
emptyBranch: end.elseStatement !== undefined &&
|
|
132
|
+
ts.isBlock(end.elseStatement) &&
|
|
133
|
+
realStatements(end.elseStatement).length === 0
|
|
134
|
+
? end.elseStatement
|
|
135
|
+
: undefined,
|
|
126
136
|
openChainEnd: end.elseStatement === undefined ? end : undefined,
|
|
127
137
|
kind: "if",
|
|
128
138
|
};
|
|
@@ -138,6 +148,11 @@ function dispatchOf(statement, variable, sourceFile) {
|
|
|
138
148
|
start: statement,
|
|
139
149
|
classes,
|
|
140
150
|
rest: (fallback?.statements ?? []).filter((inner) => !ts.isEmptyStatement(inner)),
|
|
151
|
+
emptyBranch: fallback !== undefined &&
|
|
152
|
+
ts.isDefaultClause(fallback) &&
|
|
153
|
+
fallback.statements.every((inner) => ts.isEmptyStatement(inner))
|
|
154
|
+
? fallback
|
|
155
|
+
: undefined,
|
|
141
156
|
openChainEnd: undefined,
|
|
142
157
|
kind: "switch",
|
|
143
158
|
};
|
|
@@ -155,11 +170,69 @@ function ignoringHeadline(classes, variable) {
|
|
|
155
170
|
function headline(classes) {
|
|
156
171
|
return fitted((cut) => `\`catch\` ignores errors other than ${codeList(classes, cut)}`);
|
|
157
172
|
}
|
|
173
|
+
/** The three readings of a chain with no branch for the rest: rethrow, handle, or drop on purpose. */
|
|
158
174
|
function hint(dispatch, variable) {
|
|
159
175
|
if (dispatch.kind === "switch") {
|
|
160
|
-
return
|
|
176
|
+
return [
|
|
177
|
+
"one of",
|
|
178
|
+
withExample("- end the switch with a case that rethrows the rest, so they reach the caller", [
|
|
179
|
+
"default:",
|
|
180
|
+
` throw ${variable};`,
|
|
181
|
+
]),
|
|
182
|
+
withExample("- or handle the rest in a `default` case, where the `…` is", [
|
|
183
|
+
"default:",
|
|
184
|
+
" …",
|
|
185
|
+
]),
|
|
186
|
+
withExample("- or, if dropping the rest is on purpose, state it in a `default` case", [
|
|
187
|
+
"default:",
|
|
188
|
+
" // other errors are dropped because …",
|
|
189
|
+
]),
|
|
190
|
+
].join("\n");
|
|
161
191
|
}
|
|
162
|
-
return
|
|
192
|
+
return [
|
|
193
|
+
"one of",
|
|
194
|
+
withExample("- end the chain with a branch that rethrows the rest, so they reach the caller", [
|
|
195
|
+
"} else {",
|
|
196
|
+
` throw ${variable};`,
|
|
197
|
+
"}",
|
|
198
|
+
]),
|
|
199
|
+
withExample("- or handle the rest in an `else`, where the `…` is", ["} else {", " …", "}"]),
|
|
200
|
+
withExample("- or, if dropping the rest is on purpose, state it in an `else` with a comment", [
|
|
201
|
+
"} else {",
|
|
202
|
+
" // other errors are dropped because …",
|
|
203
|
+
"}",
|
|
204
|
+
]),
|
|
205
|
+
].join("\n");
|
|
206
|
+
}
|
|
207
|
+
/** The hint for a last branch that does not use the error, when `restUsesError` asks it to. */
|
|
208
|
+
function restHint(variable) {
|
|
209
|
+
return [
|
|
210
|
+
"one of",
|
|
211
|
+
withExample("- rethrow the rest, so they reach the caller", [`throw ${variable};`]),
|
|
212
|
+
`- or use \`${variable}\` in the branch that handles the rest: report it, record it or wrap it`,
|
|
213
|
+
"- or, if that branch is right for every other error, set the rule's `restUsesError` option to `false`",
|
|
214
|
+
].join("\n");
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Whether the last branch is empty on purpose: an `else { … }` or a `default:` with no statement,
|
|
218
|
+
* and a comment that says why. A branch with nothing in it at all is a forgotten one.
|
|
219
|
+
*/
|
|
220
|
+
function dropsOnPurpose(dispatch, sourceFile) {
|
|
221
|
+
const branch = dispatch.emptyBranch;
|
|
222
|
+
if (branch === undefined)
|
|
223
|
+
return false;
|
|
224
|
+
let inside;
|
|
225
|
+
if (ts.isBlock(branch)) {
|
|
226
|
+
inside = branch.getText(sourceFile).slice(1, -1);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
// A comment after `default:` belongs to what follows it: read up to the next clause or the `}`.
|
|
230
|
+
const clauses = branch.parent.clauses;
|
|
231
|
+
const next = clauses[clauses.indexOf(branch) + 1];
|
|
232
|
+
const end = next === undefined ? branch.parent.getEnd() - 1 : next.getStart(sourceFile);
|
|
233
|
+
inside = sourceFile.text.slice(branch.getStart(sourceFile), end).replace(/^default\s*:/, "");
|
|
234
|
+
}
|
|
235
|
+
return /\/\/|\/\*/.test(inside);
|
|
163
236
|
}
|
|
164
237
|
/** The whitespace at the start of the line that holds `position`. */
|
|
165
238
|
function indentationAt(position, text) {
|
|
@@ -204,15 +277,16 @@ function checkCatch(clause, ctx) {
|
|
|
204
277
|
// A branch for the rest, or any statement that runs for every error after the chain.
|
|
205
278
|
const after = statements.slice(index + 1).filter((statement) => !ts.isEmptyStatement(statement));
|
|
206
279
|
const rest = [...dispatch.rest, ...after];
|
|
280
|
+
// An empty last branch with a comment is the drop, stated: nothing is guessed.
|
|
281
|
+
if (rest.length === 0 && dropsOnPurpose(dispatch, ctx.sourceFile))
|
|
282
|
+
return;
|
|
207
283
|
if (rest.length > 0) {
|
|
208
284
|
if (!ctx.options.restUsesError || mentions(rest, variable))
|
|
209
285
|
return;
|
|
210
286
|
ctx.report({
|
|
211
287
|
node: dispatch.start.getFirstToken(ctx.sourceFile) ?? dispatch.start,
|
|
212
288
|
message: ignoringHeadline(classes, variable),
|
|
213
|
-
hint:
|
|
214
|
-
`throw ${variable};`,
|
|
215
|
-
]),
|
|
289
|
+
hint: restHint(variable),
|
|
216
290
|
});
|
|
217
291
|
return;
|
|
218
292
|
}
|
|
@@ -232,7 +306,9 @@ export const catchHidesUnexpected = defineRule({
|
|
|
232
306
|
description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.",
|
|
233
307
|
summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest",
|
|
234
308
|
defaultSeverity: "error",
|
|
235
|
-
tier: "
|
|
309
|
+
tier: "addon",
|
|
310
|
+
addon: "catch-hides-unexpected",
|
|
311
|
+
offByDefault: OFF_BY_DEFAULT,
|
|
236
312
|
group: GROUP,
|
|
237
313
|
options: OPTIONS,
|
|
238
314
|
explain: EXPLAIN,
|
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
export declare const GROUP = "catch";
|
|
3
3
|
export declare const catchMissesError: import("@stateward/core").ProjectRule<import("./react/boundaries.js").ReactSummary, {
|
|
4
4
|
ignoreClasses: import("@stateward/core").StringsOption;
|
|
5
|
-
}, "catch"
|
|
5
|
+
}, "catch", Readonly<Record<string, import("@stateward/core").Json>>>;
|
|
6
6
|
//# sourceMappingURL=catch-misses-error.d.ts.map
|
|
@@ -58,7 +58,7 @@ export function post(text: string, remaining: number, show: (text: string) => vo
|
|
|
58
58
|
}
|
|
59
59
|
\`\`\`
|
|
60
60
|
|
|
61
|
-
The message shows the branch in the shape of your \`catch\`, and links to the call that throws each class. There is no quick fix.
|
|
61
|
+
The message shows the branch in the shape of your \`catch\`, and links to the call that throws each class. It keeps an \`else\` or \`default\` you already have: the branch goes before it, and the other readings are to make it rethrow, to use the error in it (then the rest is handled), or to list the class under \`ignoreClasses\`. There is no quick fix.
|
|
62
62
|
|
|
63
63
|
## Why it matters
|
|
64
64
|
|
|
@@ -72,14 +72,14 @@ What counts as handled: \`e instanceof X\` handles \`X\` and every class that ex
|
|
|
72
72
|
- errors stateward cannot see: from a package it cannot read, a callback, or a dynamic call. The message notes each call it could not see into, with the reason, and \`errors/catch-hides-unexpected\` makes sure the rest is not dropped;
|
|
73
73
|
- a class whose \`extends\` cannot be followed, or a branch whose test is not only \`instanceof\` (\`e instanceof A && e.code === 1\`, \`isAbort(e)\`, \`e.name === "AbortError"\`): it does not guess what that branch handles;
|
|
74
74
|
- errors from the JavaScript engine itself, such as reading a property of \`undefined\`;
|
|
75
|
-
- built-ins other than \`JSON.parse\`, \`JSON.stringify\`, \`new URL\`, \`decodeURIComponent\`, \`decodeURI\`, \`structuredClone\`, \`atob\`, \`fetch\`, \`toFixed\`, \`Array(n)\` and \`BigInt\`: they are taken not to throw;
|
|
75
|
+
- built-ins other than \`JSON.parse\`, \`JSON.stringify\`, \`new URL\`, \`decodeURIComponent\`, \`decodeURI\`, \`structuredClone\`, \`atob\`, \`fetch\`, reading a \`Response\` body (\`json()\`, \`text()\`, …), \`toFixed\`, \`Array(n)\` and \`BigInt\`: they are taken not to throw;
|
|
76
76
|
- promises kept in a \`let\`, a parameter or a property; getters, setters and generators.
|
|
77
77
|
|
|
78
78
|
## Getting the best from it
|
|
79
79
|
|
|
80
|
-
What the \`try\` can throw is worked out from \`throw new X(…)\` in the functions it calls, in any file; their \`@throws {X}\` tags (also on a function with no body, such as \`declare function\` or a \`.d.ts\` of your own); the built-ins above; and the packages it calls (\`stateward deps\` shows how well each package's errors are known). So throw classes, not strings, and document what a function throws with \`@throws\`. Declare a package's errors under \`facts\` in the config: \`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`.
|
|
80
|
+
What the \`try\` can throw is worked out from \`throw new X(…)\` in the functions it calls, in any file; their \`@throws {X}\` tags (also on a function with no body, such as \`declare function\` or a \`.d.ts\` of your own); the built-ins above; and the packages it calls, as their \`facts\` state (\`stateward deps\` shows how well each package's errors are known). A package is known by its types, the pack's model and your \`facts\`; its code and its doc comments are not read. So throw classes, not strings, and document what a function throws with \`@throws\`. Declare a package's errors under \`facts\` in the config: \`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`.
|
|
81
81
|
|
|
82
|
-
An error boundary's fallback is checked the same way: what the components below the boundary throw while rendering and in their effects, down to the next boundary, is its \`try\` (the hover on the boundary lists it). A fallback (react-error-boundary's \`FallbackComponent\`, \`fallbackRender\` or \`onError\`, or a boundary class's \`getDerivedStateFromError\`) that branches with \`if\` / \`else if\`, \`switch (true)\` or \`? :\` on \`error instanceof X\` needs a branch for each class the boundary can catch, or a branch for the rest that does more than return \`null\` or nothing. A fallback that does not branch on \`instanceof\`, whose tests are not only \`instanceof\`, or that is passed as anything other than a function written in place or the name of one of your functions, is left alone.
|
|
82
|
+
An error boundary's fallback is checked the same way: what the components below the boundary throw while rendering and in their effects, down to the next boundary, is its \`try\` (the hover on the boundary lists it). A fallback (react-error-boundary's \`FallbackComponent\`, \`fallbackRender\` or \`onError\`, or a boundary class's \`getDerivedStateFromError\`) that branches with \`if\` / \`else if\`, \`switch (true)\` or \`? :\` on \`error instanceof X\` needs a branch for each class the boundary can catch, or a branch for the rest that does more than return \`null\` or nothing. The message shows both, written for the kind of fallback (for a boundary class's \`getDerivedStateFromError\` it describes the branch for the rest, since the state is yours), and the \`ignoreClasses\` option with the class named. A fallback that does not branch on \`instanceof\`, whose tests are not only \`instanceof\`, or that is passed as anything other than a function written in place or the name of one of your functions, is left alone.
|
|
83
83
|
|
|
84
84
|
## Turn it on or off
|
|
85
85
|
|
|
@@ -96,26 +96,69 @@ function headline(names, via) {
|
|
|
96
96
|
return `\`catch\` does not handle ${codeList(names, cut)} ${source}`;
|
|
97
97
|
});
|
|
98
98
|
}
|
|
99
|
-
/**
|
|
100
|
-
|
|
99
|
+
/**
|
|
100
|
+
* The ways to handle a class the `catch` does not test, in the shape of the catch (M22): a branch
|
|
101
|
+
* for it (placed so the existing `else` or `default` stays), a rethrow for what is not handled,
|
|
102
|
+
* the generic branch using the error, or the class listed under `ignoreClasses`.
|
|
103
|
+
*/
|
|
104
|
+
function hint(names, variable, shape, hasFallback) {
|
|
105
|
+
const count = names.length;
|
|
106
|
+
const [handler = ""] = names;
|
|
101
107
|
const branch = count === 1 ? "it" : "each";
|
|
108
|
+
const ignore = count === 1
|
|
109
|
+
? `- or, if \`${handler}\` needs no branch, list it under the rule's \`ignoreClasses\` option`
|
|
110
|
+
: "- or, for the classes that need no branch, list them under the rule's `ignoreClasses` option";
|
|
111
|
+
const used = (where) => `- or, if the ${where} is right for ${count === 1 ? "it" : "them"}, use \`${variable}\` there: read it, log it or report it`;
|
|
102
112
|
switch (shape) {
|
|
103
113
|
case "switch":
|
|
104
|
-
return
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
114
|
+
return [
|
|
115
|
+
"one of",
|
|
116
|
+
hasFallback
|
|
117
|
+
? withExample(`- add a branch for ${branch}, before the \`default\` you have`, [
|
|
118
|
+
`case ${variable} instanceof ${handler}:`,
|
|
119
|
+
" …",
|
|
120
|
+
"default: // yours, unchanged",
|
|
121
|
+
])
|
|
122
|
+
: withExample(`- add a branch for ${branch}, and rethrow what you do not handle`, [
|
|
123
|
+
`case ${variable} instanceof ${handler}:`,
|
|
124
|
+
" …",
|
|
125
|
+
"default:",
|
|
126
|
+
` throw ${variable};`,
|
|
127
|
+
]),
|
|
128
|
+
...(hasFallback
|
|
129
|
+
? [
|
|
130
|
+
withExample("- or rethrow what you do not handle, in the `default` you have", [
|
|
131
|
+
"default:",
|
|
132
|
+
` throw ${variable};`,
|
|
133
|
+
]),
|
|
134
|
+
used("`default`"),
|
|
135
|
+
]
|
|
136
|
+
: []),
|
|
137
|
+
ignore,
|
|
138
|
+
].join("\n");
|
|
110
139
|
case "else":
|
|
111
|
-
return
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
140
|
+
return [
|
|
141
|
+
"one of",
|
|
142
|
+
withExample(`- add a branch for ${branch}, before the \`else\` you have`, [
|
|
143
|
+
`} else if (${variable} instanceof ${handler}) {`,
|
|
144
|
+
" …",
|
|
145
|
+
"} else { // yours, unchanged",
|
|
146
|
+
]),
|
|
147
|
+
withExample("- or rethrow what you do not handle, in the `else` you have", [
|
|
148
|
+
"} else {",
|
|
149
|
+
` throw ${variable};`,
|
|
150
|
+
"}",
|
|
151
|
+
]),
|
|
152
|
+
used("`else`"),
|
|
153
|
+
ignore,
|
|
154
|
+
].join("\n");
|
|
117
155
|
case "if":
|
|
118
|
-
return
|
|
156
|
+
return [
|
|
157
|
+
"one of",
|
|
158
|
+
withExample(`- add a branch for ${branch}, and rethrow what you do not handle after the chain`, [`if (${variable} instanceof ${handler}) {`, " …", "}", `throw ${variable};`]),
|
|
159
|
+
`- or, if what the chain does not handle is right for ${count === 1 ? "it" : "them"}, use \`${variable}\` after the chain: read it, log it or report it`,
|
|
160
|
+
ignore,
|
|
161
|
+
].join("\n");
|
|
119
162
|
default: {
|
|
120
163
|
const unreachable = shape;
|
|
121
164
|
return unreachable;
|
|
@@ -160,7 +203,7 @@ function report(seen, classes, ignored, emit) {
|
|
|
160
203
|
}
|
|
161
204
|
emit({
|
|
162
205
|
message: headline(missing.map((one) => className(one.id, classes)), via),
|
|
163
|
-
hint: hint(missing.
|
|
206
|
+
hint: hint(missing.map((one) => catchName(one.id, classes)), handler.variable, handler.dispatch === "switch" ? "switch" : handler.otherwise === null ? "if" : "else", handler.otherwise !== null),
|
|
164
207
|
location: { file: seen.file, start: handler.at[0], end: handler.at[1] },
|
|
165
208
|
related,
|
|
166
209
|
});
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
|
-
import { defineRule, option } from "@stateward/core";
|
|
2
|
+
import { codeOnOneLine, defineRule, option } from "@stateward/core";
|
|
3
3
|
import { hasModifier, isBuiltinGlobal, sameFileFunction, scanRunning, stripParentheses, throwsUncaught, } from "./syntax.js";
|
|
4
|
-
import { fitted,
|
|
4
|
+
import { fitted, withExample } from "./text.js";
|
|
5
5
|
/** The group the rule belongs to in the docs and in `stateward status`. */
|
|
6
6
|
export const GROUP = "catch";
|
|
7
7
|
const EXPLAIN = `# errors/finally-can-throw
|
|
@@ -21,7 +21,7 @@ export async function send(file: string, saved: string): Promise<void> {
|
|
|
21
21
|
}
|
|
22
22
|
\`\`\`
|
|
23
23
|
|
|
24
|
-
Give the cleanup its own \`try\` / \`catch\`,
|
|
24
|
+
Give the cleanup its own \`try\` / \`catch\` inside the \`finally\`, so it still runs when the \`try\` fails (move it out of the \`finally\` only if it should run when the \`try\` succeeds):
|
|
25
25
|
|
|
26
26
|
\`\`\`ts example-good
|
|
27
27
|
declare function upload(file: string): Promise<void>;
|
|
@@ -122,7 +122,7 @@ function causeOf(node, awaited, ctx) {
|
|
|
122
122
|
// An async function turns its throw into a rejected promise, which only an `await` rethrows.
|
|
123
123
|
if (hasModifier(declared, ts.SyntaxKind.AsyncKeyword) && !awaited)
|
|
124
124
|
return undefined;
|
|
125
|
-
const callee =
|
|
125
|
+
const callee = codeOnOneLine(stripParentheses(node.expression).getText(ctx.sourceFile));
|
|
126
126
|
return { node, subject: (cut) => `\`${cut(callee)}(…)\` can throw`, kind: "own-function" };
|
|
127
127
|
}
|
|
128
128
|
function headline(cause) {
|
|
@@ -130,7 +130,42 @@ function headline(cause) {
|
|
|
130
130
|
return "a `throw` in `finally` replaces the original error";
|
|
131
131
|
return fitted((cut) => `a throw in \`finally\` replaces the original error: ${cause.subject(cut)}`);
|
|
132
132
|
}
|
|
133
|
-
|
|
133
|
+
/** The longest statement written out in an example. */
|
|
134
|
+
const STATEMENT_MAX = 70;
|
|
135
|
+
/**
|
|
136
|
+
* The fix: catch it inside the `finally` (the statement as written, when wrapping it keeps the
|
|
137
|
+
* code working), or move it out after the `try` statement. A `throw` has nothing to catch around.
|
|
138
|
+
*/
|
|
139
|
+
function hint(cause, ctx) {
|
|
140
|
+
const statement = ts.findAncestor(cause.node, ts.isStatement);
|
|
141
|
+
const text = statement?.getText(ctx.sourceFile) ?? "";
|
|
142
|
+
const wrappable = cause.kind !== "throw" &&
|
|
143
|
+
statement !== undefined &&
|
|
144
|
+
ts.isExpressionStatement(statement) &&
|
|
145
|
+
!text.includes("\n") &&
|
|
146
|
+
text.length <= STATEMENT_MAX;
|
|
147
|
+
const out = "- or, if it should run only when the `try` succeeds, move it out of the `finally`, after the `try` statement";
|
|
148
|
+
const cannot = "- or, if it cannot throw here, state it with `// stateward-ignore errors/finally-can-throw: <why>`";
|
|
149
|
+
if (cause.kind === "throw") {
|
|
150
|
+
return [
|
|
151
|
+
"one of",
|
|
152
|
+
"- move the `throw` out of the `finally`, after the `try` statement: it then happens only when the `try` succeeds, and the original error is kept",
|
|
153
|
+
"- or, if the `throw` should replace the original error, state it with `// stateward-ignore errors/finally-can-throw: <why>`",
|
|
154
|
+
].join("\n");
|
|
155
|
+
}
|
|
156
|
+
return [
|
|
157
|
+
"one of",
|
|
158
|
+
wrappable
|
|
159
|
+
? withExample("- catch it inside the `finally`, so the original error is kept", [
|
|
160
|
+
"finally {",
|
|
161
|
+
` try { ${text} } catch (e) { … }`,
|
|
162
|
+
"}",
|
|
163
|
+
])
|
|
164
|
+
: "- catch it inside the `finally`, around the call that can throw, so the original error is kept",
|
|
165
|
+
out,
|
|
166
|
+
cannot,
|
|
167
|
+
].join("\n");
|
|
168
|
+
}
|
|
134
169
|
/** `shown` holds what is already reported: a `finally` inside a `finally` is looked at twice. */
|
|
135
170
|
function checkFinally(block, shown, ctx) {
|
|
136
171
|
let found;
|
|
@@ -143,7 +178,12 @@ function checkFinally(block, shown, ctx) {
|
|
|
143
178
|
if (found === undefined || shown.has(found.node))
|
|
144
179
|
return;
|
|
145
180
|
shown.add(found.node);
|
|
146
|
-
ctx.report({
|
|
181
|
+
ctx.report({
|
|
182
|
+
node: found.node,
|
|
183
|
+
message: headline(found),
|
|
184
|
+
hint: hint(found, ctx),
|
|
185
|
+
findingKind: found.kind,
|
|
186
|
+
});
|
|
147
187
|
}
|
|
148
188
|
export const finallyCanThrow = defineRule({
|
|
149
189
|
kind: "file",
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
export { errors } from "./plugin.js";
|
|
2
|
+
export { decidingFacts } from "./inference/needs.js";
|
|
3
|
+
export type { DecidingFacts } from "./inference/needs.js";
|
|
2
4
|
export type { ThrowsSummary } from "./inference/summary.js";
|
|
5
|
+
export type { ClassInfo, FunctionThrows, ThrowsAnalysis, ThrowsUnknown, ThrownClass, ThrowOrigin, ThrownErrors, UnknownFact, } from "./inference/analysis.js";
|
|
3
6
|
export type { ReactSummary } from "./react/boundaries.js";
|
|
4
7
|
export type { TreeSummary } from "./react/tree.js";
|
|
5
8
|
export type { MustHandleSummary } from "./must-handle-error.js";
|
|
6
|
-
export type { NarrowTrySummary } from "./narrow-try.js";
|
|
7
9
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { FactKey, Json, Location, PluginAnalysis } from "@stateward/core";
|
|
2
|
+
import type { UnknownFact } from "./solve.js";
|
|
3
|
+
export type { UnknownFact };
|
|
4
|
+
/** A place the analysis could not follow, and why. */
|
|
5
|
+
export type ThrowsUnknown = {
|
|
6
|
+
readonly location: Location;
|
|
7
|
+
/** The code there, as written: `api.get(id)`. */
|
|
8
|
+
readonly text: string;
|
|
9
|
+
/** Why it is not followed: `no declaration`, `its errors are not stated`. */
|
|
10
|
+
readonly reason: string;
|
|
11
|
+
/**
|
|
12
|
+
* The package whose facts the unknown comes from, when it does: the module of the `facts` key
|
|
13
|
+
* that names the function (`axios`, `node:path`), else the package.
|
|
14
|
+
*/
|
|
15
|
+
readonly package?: string;
|
|
16
|
+
/**
|
|
17
|
+
* What decides it: the `facts` line a package call needs (`unstated`, or `withheld` when the
|
|
18
|
+
* config's line is for other versions), a package call no key can name (`unnamed`), or a callee
|
|
19
|
+
* typed `any` (`untyped`). Absent for the other places.
|
|
20
|
+
*/
|
|
21
|
+
readonly fact?: UnknownFact;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* A class in a set of errors, by id: `builtin:TypeError` for a class of the platform (a named
|
|
25
|
+
* `DOMException` is `builtin:DOMException:AbortError`), `package:<name>#<class>` for a package's
|
|
26
|
+
* class, and the symbol id of a class of the project (`SymbolRef.id`). `certain` is false when the
|
|
27
|
+
* error may have been handled by a test the analysis does not read (`if (isNotFound(e)) return`),
|
|
28
|
+
* as the pack's own rules count it: they report only the certain ones.
|
|
29
|
+
*/
|
|
30
|
+
export type ThrownClass = {
|
|
31
|
+
readonly id: string;
|
|
32
|
+
readonly certain: boolean;
|
|
33
|
+
/**
|
|
34
|
+
* Where the error is made, in the deepest function of the project the analysis follows it to:
|
|
35
|
+
* a `throw` (`kind: "throw"`), or a call of the platform or of a package that throws or rejects
|
|
36
|
+
* with it (`kind: "call"`). Absent when only a `@throws` tag names the class.
|
|
37
|
+
*/
|
|
38
|
+
readonly origin?: ThrowOrigin;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* `text`: for a call, the function it calls as written (`api.get`); absent for a `throw`.
|
|
42
|
+
* `platform`: the call is into the platform (TypeScript's lib, Node's types, the config's
|
|
43
|
+
* `platform`), not into a package or a declaration of the project.
|
|
44
|
+
*/
|
|
45
|
+
export type ThrowOrigin = {
|
|
46
|
+
readonly kind: "throw";
|
|
47
|
+
readonly location: Location;
|
|
48
|
+
} | {
|
|
49
|
+
readonly kind: "call";
|
|
50
|
+
readonly location: Location;
|
|
51
|
+
readonly text: string;
|
|
52
|
+
/** Whether the call throws the error or returns a promise that rejects with it. */
|
|
53
|
+
readonly side: "throws" | "rejects";
|
|
54
|
+
readonly platform?: true;
|
|
55
|
+
};
|
|
56
|
+
/** A set of errors: the classes in it, and why the rest of it is unknown. */
|
|
57
|
+
export type ThrownErrors = {
|
|
58
|
+
/** Sorted by id. */
|
|
59
|
+
readonly classes: readonly ThrownClass[];
|
|
60
|
+
/** The places not followed, in file order: none when the set is exactly `classes`. */
|
|
61
|
+
readonly unknown: readonly ThrowsUnknown[];
|
|
62
|
+
/** Present when more places were not followed than `unknown` lists. */
|
|
63
|
+
readonly more?: true;
|
|
64
|
+
};
|
|
65
|
+
/** What calling one function can throw, and what the promise it returns can reject with. */
|
|
66
|
+
export type FunctionThrows = {
|
|
67
|
+
/** The function's name and where its name is. */
|
|
68
|
+
readonly name: string;
|
|
69
|
+
readonly location: Location;
|
|
70
|
+
readonly throws: ThrownErrors;
|
|
71
|
+
readonly rejects: ThrownErrors;
|
|
72
|
+
};
|
|
73
|
+
/**
|
|
74
|
+
* The analysis `errors/throws`: every named function of the project, by the symbol id of its
|
|
75
|
+
* declaration (`SymbolRef.id`, as `TypeQueries.symbolAt` gives it), sorted by id. A function's
|
|
76
|
+
* `@throws` tags, when it has them, are what it throws; otherwise its body is followed through
|
|
77
|
+
* the calls it makes, into other files and into packages.
|
|
78
|
+
*/
|
|
79
|
+
export type ThrowsAnalysis = {
|
|
80
|
+
readonly functions: Readonly<Record<string, FunctionThrows>>;
|
|
81
|
+
/**
|
|
82
|
+
* Every class the functions name, and every class those extend, by id: so a reader can tell
|
|
83
|
+
* that a class extends another (`NotFound extends HttpException`).
|
|
84
|
+
*/
|
|
85
|
+
readonly classes: Readonly<Record<string, ClassInfo>>;
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* A class of `ThrowsAnalysis.classes`: its name, the id of the class it extends (null for none),
|
|
89
|
+
* and `open` when what it extends cannot be followed (a mixin, a name that does not resolve, a
|
|
90
|
+
* class the summaries do not describe), so whether it is a subclass of another is not known.
|
|
91
|
+
*/
|
|
92
|
+
export type ClassInfo = {
|
|
93
|
+
readonly name: string;
|
|
94
|
+
readonly parent: string | null;
|
|
95
|
+
readonly open: boolean;
|
|
96
|
+
/** The instance properties the class declares itself (`ClassFact.fields`); empty when not read. */
|
|
97
|
+
readonly fields: readonly string[];
|
|
98
|
+
/** With `open`: the parent's name as its declaration writes it, when it does not resolve. */
|
|
99
|
+
readonly declared?: string;
|
|
100
|
+
/** With `open`, for a package's class: the package's version that runs, when it is known. */
|
|
101
|
+
readonly version?: string;
|
|
102
|
+
/** With `open`, for a package's class: the `facts` key that names it (`ClassFact.key`). */
|
|
103
|
+
readonly key?: FactKey;
|
|
104
|
+
};
|
|
105
|
+
/** Solves the summaries into the published shape. */
|
|
106
|
+
export declare function throwsAnalysis(summaries: ReadonlyMap<string, Json>): ThrowsAnalysis;
|
|
107
|
+
/** `Plugin.analyses.throws` of the errors pack. */
|
|
108
|
+
export declare const throws: PluginAnalysis;
|
|
109
|
+
//# sourceMappingURL=analysis.d.ts.map
|