Skip to content

Commit 45c4a59

Browse files
committed
feat(json): improve error
1 parent 033879d commit 45c4a59

File tree

2 files changed

+11
-19
lines changed

2 files changed

+11
-19
lines changed

packages/json/src/json.index.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
export * from "./json.bundle.ts";
22
export * as json from "./json.bundle.ts";
3-
export { JsonParseException } from "./json.lib.ts";

packages/json/src/json.lib.ts

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,14 @@ export const serialize = <SHAPE = unknown>(
1818
data: SHAPE,
1919
config: { pretty?: boolean; schema?: ZodSchema<any, SHAPE> } = {},
2020
) => {
21-
const validatedData = config.schema ? config.schema.parse(data) : data;
22-
return JSON.stringify(validatedData, null, config.pretty ? 2 : undefined);
21+
try {
22+
const validatedData = config.schema ? config.schema.parse(data) : data;
23+
return JSON.stringify(validatedData, null, config.pretty ? 2 : undefined);
24+
} catch (error) {
25+
throw new Error(`Failed to serialize JSON`, {
26+
cause: error,
27+
});
28+
}
2329
};
2430

2531
/**
@@ -39,22 +45,9 @@ export const deserialize = <SHAPE = unknown>(
3945
if (config.schema) return config.schema.parse(validatedData);
4046
return validatedData;
4147
} catch (error) {
42-
throw new JsonParseException(content.toString(), error);
48+
throw new Error(`Failed to parse JSON`, {
49+
cause: error,
50+
});
4351
}
4452
};
4553

46-
export class JsonParseException extends Error {
47-
constructor(value: string, cause?: any) {
48-
const message = `
49-
Failed to parse JSON
50-
51-
[JSON String Value]:
52-
${value}
53-
54-
[Cause]:
55-
${cause instanceof Error ? cause.message : String(cause)}
56-
`;
57-
58-
super(message, { cause });
59-
}
60-
}

0 commit comments

Comments
 (0)