errors: add toError utility and migrate assertError usages

Add a `toError` utility function to `@backstage/errors` that converts
unknown values to `ErrorLike` objects. If the value is already error-like
it is returned as-is. Strings are used directly as the error message, and
other values are stringified with a fallback to JSON.stringify to avoid
unhelpful `[object Object]` messages.

Non-error causes passed to `CustomErrorBase` are now converted and stored
using `toError` rather than discarded. Existing `assertError` call sites
across the codebase are migrated to `toError`.

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
Made-with: Cursor
This commit is contained in:
Patrik Oldsberg
2026-04-03 01:33:34 +02:00
parent 3cdf048f77
commit b2319ffe45
70 changed files with 400 additions and 345 deletions
+5 -8
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { assertError, ForwardedError } from '@backstage/errors';
import { ForwardedError, toError } from '@backstage/errors';
import { targetPaths } from '@backstage/cli-common';
import { runOutput } from '@backstage/cli-common';
@@ -28,13 +28,10 @@ export async function runGit(...args: string[]) {
});
return stdout.trim().split(/\r\n|\r|\n/);
} catch (error) {
assertError(error);
if (
'code' in error &&
typeof (error as { code?: number }).code === 'number'
) {
const code = (error as { code?: number }).code;
const stderr = (error as { stderr?: string }).stderr;
const err = toError(error);
if ('code' in err && typeof (err as { code?: number }).code === 'number') {
const code = (err as { code?: number }).code;
const stderr = (err as { stderr?: string }).stderr;
const msg = stderr?.trim() ?? `with exit code ${code}`;
throw new Error(`git ${args[0]} failed, ${msg}`);
}
+1 -6
View File
@@ -14,11 +14,7 @@
* limitations under the License.
*/
import {
assertError,
ForwardedError,
NotImplementedError,
} from '@backstage/errors';
import { ForwardedError, NotImplementedError } from '@backstage/errors';
import { PackageInfo, PackageManager } from '../PackageManager';
import { Lockfile } from '../Lockfile';
import { YarnVersion } from './types';
@@ -96,7 +92,6 @@ function detectYarnVersion(dir?: string): Promise<YarnVersion> {
: 'berry';
return { version: versionString, codename };
} catch (error) {
assertError(error);
throw new ForwardedError('Failed to determine yarn version', error);
}
});