0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-20 22:12:38 -05:00

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 - 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 {} + 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 # TODO: enable when the script is updated
id: changes # - name: Check if docs changed
uses: dorny/paths-filter@v2 # id: changes
with: # uses: dorny/paths-filter@v2
filters: | # with:
docs: # filters: |
- 'packages/integrations/*/README.md' # docs:
- 'packages/astro/src/@types/astro.ts' # - 'packages/integrations/*/README.md'
- 'packages/astro/src/core/errors/errors-data.ts' # - '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' }} # - name: Build autogenerated docs pages from current astro branch
run: cd smoke/docs && pnpm docgen && pnpm docgen:errors && pnpm docgen:integrations # if: ${{ steps.changes.outputs.docs == 'true' }}
env: # run: cd smoke/docs && pnpm docgen && pnpm docgen:errors && pnpm docgen:integrations
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # env:
SOURCE_REPO: ${{ github.event.pull_request.head.repo.full_name || github.event.repository.full_name }} # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SOURCE_BRANCH: ${{ github.head_ref || github.ref_name }} # 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 - name: Test
run: pnpm run test:smoke run: pnpm run test:smoke

View file

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

View file

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

View file

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

View file

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

View file

@ -8,7 +8,7 @@
**Error Format** **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 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. - 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: Message:
- Begin with **what happened** and **why**. (ex: `Could not use {feature} because Server-side Rendering is not enabled.`) - 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.`) - 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. - 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`. - 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 { getHighlighter } from 'shiki';
import type { ErrorPayload } from 'vite'; import type { ErrorPayload } from 'vite';
import type { ModuleLoader } from '../../module-loader/index.js'; 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 { AstroError, type ErrorWithMetadata } from '../errors.js';
import { createSafeError } from '../utils.js'; import { createSafeError } from '../utils.js';
import type { SSRLoadedRenderer } from './../../../@types/astro.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 // https://github.com/vitejs/vite/blob/ee7c28a46a6563d54b828af42570c55f16b15d2c/packages/vite/src/node/ssr/ssrModuleLoader.ts#L91
let importName: string | undefined; let importName: string | undefined;
if ((importName = safeError.message.match(/Failed to load url (.*?) \(resolved id:/)?.[1])) { 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.name = 'FailedToLoadModuleSSR';
safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName); safeError.message = FailedToLoadModuleSSR.message(importName);
safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint; safeError.hint = FailedToLoadModuleSSR.hint;
const line = lns.findIndex((ln) => ln.includes(importName!)); const line = lns.findIndex((ln) => ln.includes(importName!));
if (line !== -1) { if (line !== -1) {
@ -68,8 +68,8 @@ export function enhanceViteSSRError({
fileId?.match(/\.mdx$/) fileId?.match(/\.mdx$/)
) { ) {
safeError = new AstroError({ safeError = new AstroError({
...AstroErrorData.MdxIntegrationMissingError, ...MdxIntegrationMissingError,
message: AstroErrorData.MdxIntegrationMissingError.message(JSON.stringify(fileId)), message: MdxIntegrationMissingError.message(JSON.stringify(fileId)),
location: safeError.loc, location: safeError.loc,
stack: safeError.stack, stack: safeError.stack,
}) as ErrorWithMetadata; }) as ErrorWithMetadata;
@ -80,10 +80,10 @@ export function enhanceViteSSRError({
const globPattern = safeError.message.match(/glob: "(.+)" \(/)?.[1]; const globPattern = safeError.message.match(/glob: "(.+)" \(/)?.[1];
if (globPattern) { if (globPattern) {
safeError.message = AstroErrorData.InvalidGlob.message(globPattern); safeError.message = InvalidGlob.message(globPattern);
safeError.name = 'InvalidGlob'; safeError.name = 'InvalidGlob';
safeError.hint = AstroErrorData.InvalidGlob.hint; safeError.hint = InvalidGlob.hint;
safeError.title = AstroErrorData.InvalidGlob.title; safeError.title = InvalidGlob.title;
const line = lns.findIndex((ln) => ln.includes(globPattern)); 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 message = renderErrorMarkdown(err.message.trim(), 'html');
const hint = err.hint ? renderErrorMarkdown(err.hint.trim(), 'html') : undefined; const hint = err.hint ? renderErrorMarkdown(err.hint.trim(), 'html') : undefined;
const hasDocs = err.name in AstroErrorData; const hasDocs = !!err.name;
const docslink = hasDocs const docslink = hasDocs
? `https://docs.astro.build/en/reference/errors/${getKebabErrorName(err.name)}/` ? `https://docs.astro.build/en/reference/errors/${getKebabErrorName(err.name)}/`
: undefined; : undefined;

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

@ -1,7 +1,6 @@
import type { YAMLException } from 'js-yaml'; import type { YAMLException } from 'js-yaml';
import type { ErrorPayload as ViteErrorPayload } from 'vite'; import type { ErrorPayload as ViteErrorPayload } from 'vite';
import type { SSRError } from '../../@types/astro.js'; import type { SSRError } from '../../@types/astro.js';
import { AstroErrorData, type ErrorData } from './errors-data.js';
/** /**
* Get the line and character based on the offset * Get the line and character based on the offset
@ -105,14 +104,3 @@ export function createSafeError(err: any): Error {
export function normalizeLF(code: string) { export function normalizeLF(code: string) {
return code.replace(/\r\n|\r(?!\n)|\n/g, '\n'); 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 type { PluginObj } from '@babel/core';
import * as t from '@babel/types'; 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 { AstroError } from '../core/errors/errors.js';
import { resolvePath } from '../core/util.js'; import { resolvePath } from '../core/util.js';
import type { PluginMetadata } from '../vite-plugin-astro/types'; 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 (id === resolvedVirtualModuleId) {
if (!config.experimental.viewTransitions) { if (!config.experimental.viewTransitions) {
throw new AstroError({ throw new AstroError({
name: 'TransitionError',
title: 'Experimental View Transitions not enabled', title: 'Experimental View Transitions not enabled',
message: `View Transitions support is experimental. To enable update your config to include: 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); return matter(source);
} catch (err: any) { } catch (err: any) {
const markdownError = new MarkdownError({ const markdownError = new MarkdownError({
name: 'MarkdownError',
message: err.message, message: err.message,
stack: err.stack, stack: err.stack,
location: { location: {

View file

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