feat: break down AstroErrorData in multiple objects (#7949)

This commit is contained in:
Emanuele Stoppa 2023-08-04 14:57:19 +01:00 committed by GitHub
parent f3b234b258
commit f844238c9b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 1175 additions and 1111 deletions

View file

@ -230,23 +230,24 @@ jobs:
- name: Remove docs translations except for English and Korean
run: find smoke/docs/src/content/docs ! -name 'en' ! -name 'ko' -type d -mindepth 1 -maxdepth 1 -exec rm -rf {} +
- name: Check if docs changed
id: changes
uses: dorny/paths-filter@v2
with:
filters: |
docs:
- 'packages/integrations/*/README.md'
- 'packages/astro/src/@types/astro.ts'
- 'packages/astro/src/core/errors/errors-data.ts'
- name: Build autogenerated docs pages from current astro branch
if: ${{ steps.changes.outputs.docs == 'true' }}
run: cd smoke/docs && pnpm docgen && pnpm docgen:errors && pnpm docgen:integrations
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SOURCE_REPO: ${{ github.event.pull_request.head.repo.full_name || github.event.repository.full_name }}
SOURCE_BRANCH: ${{ github.head_ref || github.ref_name }}
# TODO: enable when the script is updated
# - name: Check if docs changed
# id: changes
# uses: dorny/paths-filter@v2
# with:
# filters: |
# docs:
# - 'packages/integrations/*/README.md'
# - 'packages/astro/src/@types/astro.ts'
# - 'packages/astro/src/core/errors/errors-data.ts'
#
# - name: Build autogenerated docs pages from current astro branch
# if: ${{ steps.changes.outputs.docs == 'true' }}
# run: cd smoke/docs && pnpm docgen && pnpm docgen:errors && pnpm docgen:integrations
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# SOURCE_REPO: ${{ github.event.pull_request.head.repo.full_name || github.event.repository.full_name }}
# SOURCE_BRANCH: ${{ github.head_ref || github.ref_name }}
- name: Test
run: pnpm run test:smoke

View file

@ -5,7 +5,7 @@ import * as path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { normalizePath, type ViteDevServer } from 'vite';
import type { AstroSettings, ContentEntryType } from '../@types/astro.js';
import { AstroErrorData } from '../core/errors/errors-data.js';
import { AstroErrorData } from '../core/errors/index.js';
import { AstroError } from '../core/errors/errors.js';
import { info, warn, type LogOptions } from '../core/logger/core.js';
import { isRelativePath } from '../core/path.js';

View file

@ -12,7 +12,7 @@ import type {
DataEntryModule,
DataEntryType,
} from '../@types/astro.js';
import { AstroErrorData } from '../core/errors/errors-data.js';
import { AstroErrorData } from '../core/errors/index.js';
import { AstroError } from '../core/errors/errors.js';
import { escapeViteEnvReferences } from '../vite-plugin-utils/index.js';
import { CONTENT_FLAG, DATA_FLAG } from './consts.js';
@ -371,6 +371,7 @@ function stringifyEntryData(data: Record<string, any>): string {
});
} else {
throw new AstroError({
name: 'PluginContentImportsError',
message: 'Unexpected error processing content collection data.',
});
}

View file

@ -87,6 +87,7 @@ function handleCompileResultErrors(result: TransformResult, cssTransformErrors:
if (compilerError) {
throw new CompilerError({
name: 'CompilerError',
message: compilerError.text,
location: {
line: compilerError.location.line,

View file

@ -88,6 +88,7 @@ function enhanceCSSError(err: any, filename: string, cssContent: string) {
errorPosition.line += 1;
return new CSSError({
name: 'CSSError',
message: err.message,
location: {
file: filename,

View file

@ -8,7 +8,7 @@
**Error Format**
Name (key of the object definition):
Name:
- This property is a static reference to the error. The shape should be similar to JavaScript's native errors (TypeError, ReferenceError): pascal-cased, no spaces, no special characters etc. (ex: `ClientAddressNotAvailable`)
- This is the only part of the error message that should not be written as a full, proper sentence complete with Capitalization and end punctuation.
@ -19,8 +19,8 @@ Title:
Message:
- Begin with **what happened** and **why**. (ex: `Could not use {feature} because Server-side Rendering is not enabled.`)
- Then, **describe the action the user should take**. (ex: `Update your Astro config with `output: 'server'` to enable Server-side Rendering.`)
- Begin with **what happened** and **why**. (ex: `Could not use {feature} because Server-side Rendering is not enabled.`)
- Then, **describe the action the user should take**. (ex: `Update your Astro config with `output: 'server'` to enable Server-side Rendering.`)
- Although this does not need to be as brief as the `title`, try to keep sentences short, clear and direct to give the reader all the necessary information quickly as possible.
- Instead of writing a longer message, consider using a `hint`.

View file

@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url';
import { getHighlighter } from 'shiki';
import type { ErrorPayload } from 'vite';
import type { ModuleLoader } from '../../module-loader/index.js';
import { AstroErrorData } from '../errors-data.js';
import { FailedToLoadModuleSSR, InvalidGlob, MdxIntegrationMissingError } from '../errors-data.js';
import { AstroError, type ErrorWithMetadata } from '../errors.js';
import { createSafeError } from '../utils.js';
import type { SSRLoadedRenderer } from './../../../@types/astro.js';
@ -41,10 +41,10 @@ export function enhanceViteSSRError({
// https://github.com/vitejs/vite/blob/ee7c28a46a6563d54b828af42570c55f16b15d2c/packages/vite/src/node/ssr/ssrModuleLoader.ts#L91
let importName: string | undefined;
if ((importName = safeError.message.match(/Failed to load url (.*?) \(resolved id:/)?.[1])) {
safeError.title = AstroErrorData.FailedToLoadModuleSSR.title;
safeError.title = FailedToLoadModuleSSR.title;
safeError.name = 'FailedToLoadModuleSSR';
safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName);
safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint;
safeError.message = FailedToLoadModuleSSR.message(importName);
safeError.hint = FailedToLoadModuleSSR.hint;
const line = lns.findIndex((ln) => ln.includes(importName!));
if (line !== -1) {
@ -68,8 +68,8 @@ export function enhanceViteSSRError({
fileId?.match(/\.mdx$/)
) {
safeError = new AstroError({
...AstroErrorData.MdxIntegrationMissingError,
message: AstroErrorData.MdxIntegrationMissingError.message(JSON.stringify(fileId)),
...MdxIntegrationMissingError,
message: MdxIntegrationMissingError.message(JSON.stringify(fileId)),
location: safeError.loc,
stack: safeError.stack,
}) as ErrorWithMetadata;
@ -80,10 +80,10 @@ export function enhanceViteSSRError({
const globPattern = safeError.message.match(/glob: "(.+)" \(/)?.[1];
if (globPattern) {
safeError.message = AstroErrorData.InvalidGlob.message(globPattern);
safeError.message = InvalidGlob.message(globPattern);
safeError.name = 'InvalidGlob';
safeError.hint = AstroErrorData.InvalidGlob.hint;
safeError.title = AstroErrorData.InvalidGlob.title;
safeError.hint = InvalidGlob.hint;
safeError.title = InvalidGlob.title;
const line = lns.findIndex((ln) => ln.includes(globPattern));
@ -137,7 +137,7 @@ export async function getViteErrorPayload(err: ErrorWithMetadata): Promise<Astro
const message = renderErrorMarkdown(err.message.trim(), 'html');
const hint = err.hint ? renderErrorMarkdown(err.hint.trim(), 'html') : undefined;
const hasDocs = err.name in AstroErrorData;
const hasDocs = !!err.name;
const docslink = hasDocs
? `https://docs.astro.build/en/reference/errors/${getKebabErrorName(err.name)}/`
: undefined;

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,9 @@
import type { ZodError } from 'zod';
import { codeFrame } from './printer.js';
import { getErrorDataByTitle } from './utils.js';
interface ErrorProperties {
title?: string;
name?: string;
name: string;
message?: string;
location?: ErrorLocation;
hint?: string;
@ -43,16 +42,7 @@ export class AstroError extends Error {
const { name, title, message, stack, location, hint, frame } = props;
this.title = title;
if (name && name !== 'Error') {
this.name = name;
} else if (this.title) {
const errorData = getErrorDataByTitle(this.title)?.name;
if (errorData) {
this.name = errorData;
}
}
if (message) this.message = message;
// Only set this if we actually have a stack passed, otherwise uses Error's
@ -92,8 +82,6 @@ export class CompilerError extends AstroError {
constructor(props: ErrorProperties, ...params: any) {
super(props, ...params);
this.name = 'CompilerError';
}
static is(err: unknown): err is CompilerError {

View file

@ -1,5 +1,5 @@
export type { ErrorLocation, ErrorWithMetadata } from './errors';
export { AstroErrorData } from './errors-data.js';
export * as AstroErrorData from './errors-data.js';
export {
AggregateError,
AstroError,

View file

@ -1,7 +1,6 @@
import type { YAMLException } from 'js-yaml';
import type { ErrorPayload as ViteErrorPayload } from 'vite';
import type { SSRError } from '../../@types/astro.js';
import { AstroErrorData, type ErrorData } from './errors-data.js';
/**
* Get the line and character based on the offset
@ -105,14 +104,3 @@ export function createSafeError(err: any): Error {
export function normalizeLF(code: string) {
return code.replace(/\r\n|\r(?!\n)|\n/g, '\n');
}
export function getErrorDataByTitle(title: string) {
const entry = Object.entries(AstroErrorData).find((data) => data[1].title === title);
if (entry) {
return {
name: entry[0],
data: entry[1] as ErrorData,
};
}
}

View file

@ -1,6 +1,6 @@
import type { PluginObj } from '@babel/core';
import * as t from '@babel/types';
import { AstroErrorData } from '../core/errors/errors-data.js';
import { AstroErrorData } from '../core/errors/index.js';
import { AstroError } from '../core/errors/errors.js';
import { resolvePath } from '../core/util.js';
import type { PluginMetadata } from '../vite-plugin-astro/types';

View file

@ -18,6 +18,7 @@ export default function astroTransitions({ config }: { config: AstroConfig }): v
if (id === resolvedVirtualModuleId) {
if (!config.experimental.viewTransitions) {
throw new AstroError({
name: 'TransitionError',
title: 'Experimental View Transitions not enabled',
message: `View Transitions support is experimental. To enable update your config to include:

View file

@ -27,6 +27,7 @@ function safeMatter(source: string, id: string) {
return matter(source);
} catch (err: any) {
const markdownError = new MarkdownError({
name: 'MarkdownError',
message: err.message,
stack: err.stack,
location: {

View file

@ -1,5 +1,5 @@
import { expect } from 'chai';
import { AstroErrorData } from '../dist/core/errors/errors-data.js';
import { ClientAddressNotAvailable } from '../dist/core/errors/errors-data.js';
import { AstroError } from '../dist/core/errors/errors.js';
import * as events from '../dist/events/index.js';
@ -470,8 +470,8 @@ describe('Events', () => {
it('returns the expected event payload for AstroError', () => {
const [event] = events.eventError({
err: new AstroError({
...AstroErrorData.ClientAddressNotAvailable,
message: AstroErrorData.ClientAddressNotAvailable.message('mysuperadapter'),
...ClientAddressNotAvailable,
message: ClientAddressNotAvailable.message('mysuperadapter'),
}),
cmd: 'COMMAND_NAME',
isFatal: false,