feat: expose user astro error (#8012)

This commit is contained in:
Emanuele Stoppa 2023-08-11 15:57:29 +01:00 committed by GitHub
parent 519a1c4e84
commit 866ed4098e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 38 additions and 2 deletions

View file

@ -0,0 +1,5 @@
---
'astro': minor
---
Add a new `astro/errors` module. Developers can import `AstroUserError`, and provide a `message` and an optional `hint`

View file

@ -69,6 +69,7 @@
"types": "./zod.d.ts",
"default": "./zod.mjs"
},
"./errors": "./dist/core/errors/userError.js",
"./middleware": {
"types": "./dist/core/middleware/index.d.ts",
"default": "./dist/core/middleware/index.js"

View file

@ -19,6 +19,7 @@ export interface ErrorLocation {
type ErrorTypes =
| 'AstroError'
| 'AstroUserError'
| 'CompilerError'
| 'CSSError'
| 'MarkdownError'
@ -171,3 +172,25 @@ export interface ErrorWithMetadata {
};
cause?: any;
}
/**
* Special error that is exposed to users.
* Compared to AstroError, it contains a subset of information.
*/
export class AstroUserError extends Error {
type: ErrorTypes = 'AstroUserError';
/**
* A message that explains to the user how they can fix the error.
*/
hint: string | undefined;
name = 'AstroUserError';
constructor(message: string, hint?: string) {
super();
this.message = message;
this.hint = hint;
}
static is(err: unknown): err is AstroUserError {
return (err as AstroUserError).type === 'AstroUserError';
}
}

View file

@ -7,6 +7,7 @@ export {
CompilerError,
MarkdownError,
isAstroError,
AstroUserError,
} from './errors.js';
export { codeFrame } from './printer.js';
export { createSafeError, positionAt } from './utils.js';

View file

@ -0,0 +1 @@
export { AstroUserError as AstroError } from './errors.js';

View file

@ -17,7 +17,12 @@ import {
import type { ResolvedServerUrls } from 'vite';
import type { ZodError } from 'zod';
import { renderErrorMarkdown } from './errors/dev/utils.js';
import { AstroError, CompilerError, type ErrorWithMetadata } from './errors/index.js';
import {
AstroError,
CompilerError,
type ErrorWithMetadata,
AstroUserError,
} from './errors/index.js';
import { emoji, padMultilineString } from './util.js';
const PREFIX_PADDING = 6;
@ -198,7 +203,7 @@ export function formatConfigErrorMessage(err: ZodError) {
}
export function formatErrorMessage(err: ErrorWithMetadata, args: string[] = []): string {
const isOurError = AstroError.is(err) || CompilerError.is(err);
const isOurError = AstroError.is(err) || CompilerError.is(err) || AstroUserError.is(err);
args.push(
`${bgRed(black(` error `))}${red(