Skip to content

Commit 954a195

Browse files
committed
fix(napi/oxlint): loadPlugin never throw error (#12478)
Fix an edge case bug. Ensure `loadPlugin` never throws, even if user code does something wacky like throwing `null` or `{ get message() { throw new Error("ha ha ha got you!") } }`.
1 parent 7e4959a commit 954a195

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

napi/oxlint2/src-js/index.js

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { createRequire } from 'node:module';
22
import { lint } from './bindings.js';
33
import { DATA_POINTER_POS_32, SOURCE_LEN_POS_32 } from './generated/constants.cjs';
4+
import { getErrorMessage } from './utils.js';
45
import { addVisitorToCompiled, compiledVisitor, finalizeCompiledVisitor, initCompiledVisitor } from './visitor.js';
56

67
// Import methods and objects from `oxc-parser`.
@@ -34,11 +35,8 @@ const registeredRules = [];
3435
async function loadPlugin(path) {
3536
try {
3637
return await loadPluginImpl(path);
37-
} catch (error) {
38-
const errorMessage = 'message' in error && typeof error.message === 'string'
39-
? error.message
40-
: 'An unknown error occurred';
41-
return JSON.stringify({ Failure: errorMessage });
38+
} catch (err) {
39+
return JSON.stringify({ Failure: getErrorMessage(err) });
4240
}
4341
}
4442

napi/oxlint2/src-js/utils.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* Get error message from an error.
3+
*
4+
* `err` is expected to be an `Error` object, but can be anything.
5+
*
6+
* This function will never throw, and always returns a string, even if:
7+
*
8+
* * `err` is `null` or `undefined`.
9+
* * `err` is an object with a getter for `message` property which throws.
10+
* * `err` has a getter for `message` property which returns a different value each time it's accessed.
11+
*
12+
* @param {*} err - Error
13+
* @returns {string} - Error message
14+
*/
15+
export function getErrorMessage(err) {
16+
try {
17+
const { message } = err;
18+
if (typeof message === 'string' && message !== '') return message;
19+
} catch {}
20+
21+
return 'Unknown error';
22+
}

0 commit comments

Comments
 (0)