Skip to content

Commit

Permalink
feat: format zod parsing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
lars-berger committed Feb 17, 2024
1 parent 68b91cc commit 7c2edd1
Show file tree
Hide file tree
Showing 7 changed files with 47 additions and 25 deletions.
17 changes: 6 additions & 11 deletions packages/client-api/src/init-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import {
runWithOwner,
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { message } from '@tauri-apps/plugin-dialog';
import { message as messageDialog } from '@tauri-apps/plugin-dialog';

import {
getStyleBuilder,
getParsedElementConfig,
getChildConfigs,
type GlobalConfig,
TemplatePropertyError,
} from './user-config';
import { getElementProviders } from './providers';
import type { ElementContext } from './element-context.model';
Expand Down Expand Up @@ -107,17 +106,13 @@ export async function initElement(

return elementContext as ElementContext;
} catch (err) {
logger.error(
'Error initializing window:',
//@ts-ignore
Object.keys(err),
err instanceof TemplatePropertyError,
err,
);
message((err as Error).message, {
title: 'Encountered an error!',
logger.error('Failed to initialize element:', err);

messageDialog((err as Error)?.message ?? 'Unknown reason.', {
title: 'Failed to initialize element!',
type: 'error',
});

throw err;
}
}
15 changes: 9 additions & 6 deletions packages/client-api/src/init-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type UserConfig,
getUserConfig,
getStyleBuilder,
parseWithSchema,
} from './user-config';
import {
getOpenWindowArgs,
Expand Down Expand Up @@ -57,7 +58,8 @@ export async function initWindowAsync(): Promise<WindowContext> {
);
}

const globalConfig = GlobalConfigSchema.strip().parse(
const globalConfig = parseWithSchema(
GlobalConfigSchema.strip(),
(config as UserConfig)?.global ?? {},
);

Expand Down Expand Up @@ -110,12 +112,13 @@ export async function initWindowAsync(): Promise<WindowContext> {
} catch (err) {
logger.error('Failed to initialize window:', err);

let message = (err as Error)?.message
? `Failed to initialize window.\n\n${(err as Error).message}`
: `Failed to initialize window.`;
messageDialog((err as Error)?.message ?? 'Unknown reason.', {
title: 'Failed to initialize window!',
type: 'error',
});

// Show error dialog and exit.
messageDialog(message, { title: 'Fatal error :(', type: 'error' });
// Error during window initialization is unrecoverable, so we close
// the window.
await getCurrentWindow().close();

throw err;
Expand Down
5 changes: 3 additions & 2 deletions packages/client-api/src/providers/get-element-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
} from 'solid-js';
import { createStore } from 'solid-js/store';

import { ProvidersConfigSchema } from '~/user-config';
import { ProvidersConfigSchema, parseWithSchema } from '~/user-config';
import type { ElementContext } from '~/element-context.model';
import { createProvider } from './create-provider';
import type { PickPartial } from '~/utils';
Expand Down Expand Up @@ -35,7 +35,8 @@ export async function getElementProviders(
* Get map of element providers.
*/
async function getElementProviders() {
const providerConfigs = ProvidersConfigSchema.parse(
const providerConfigs = parseWithSchema(
ProvidersConfigSchema,
(elementContext.rawConfig as Record<string, unknown>)?.providers ??
[],
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
TemplateConfigSchema,
WindowConfigSchemaP1,
TemplatePropertyError,
parseWithSchema,
} from '~/user-config';
import type { PickPartial } from '~/utils';

Expand Down Expand Up @@ -66,7 +67,7 @@ export function getParsedElementConfig(
// TODO: Add logging for updated config here.
const newConfig = Object.fromEntries(newConfigEntries);

return schema.parse(newConfig);
return parseWithSchema(schema, newConfig);
}

return parsedConfig;
Expand Down
5 changes: 0 additions & 5 deletions packages/client-api/src/user-config/get-user-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,6 @@ export async function getUserConfig() {

return configObj;
} catch (err) {
console.log('err', err.constructor.name);
if (err instanceof YAMLParseError) {
err.
}

throw new Error(
`Problem reading config file: ${(err as Error).message}`,
);
Expand Down
1 change: 1 addition & 0 deletions packages/client-api/src/user-config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './get-parsed-element-config';
export * from './get-style-builder';
export * from './get-user-config';
export * from './global-config.model';
export * from './parse-with-schema';
export * from './shared';
export * from './user-config.model';
export * from './window';
26 changes: 26 additions & 0 deletions packages/client-api/src/user-config/parse-with-schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { ZodError, type z } from 'zod';

/**
* Parse a value with error formatting.
*/
export function parseWithSchema<T extends z.ZodType>(
schema: T,
value: unknown,
): z.infer<T> {
try {
return schema.parse(value);
} catch (err) {
if (err instanceof ZodError && err.errors.length) {
const [firstError] = err.errors;
const { message, path } = firstError!;
const fullPath = path.join('.');

throw new Error(
`Property '${fullPath}' in config isn't valid.\n` +
`⚠️ ${message}`,
);
}

throw new Error('Failed to parse config.');
}
}

0 comments on commit 7c2edd1

Please sign in to comment.