Skip to content

Commit 7d5a7f3

Browse files
committed
better error reporting
1 parent 3156365 commit 7d5a7f3

File tree

2 files changed

+35
-11
lines changed

2 files changed

+35
-11
lines changed

src/index.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,25 @@ hash:0:tpl.template:0:1
286286
const cont = await api.getContent(repHash("0"));
287287
expect(cont).toEqual(content);
288288
});
289+
290+
test("Validation Error", async () => {
291+
const realHash = repHash("1");
292+
const file = `3
293+
${realHash}:0:doc.content:0:1
294+
hash:0:doc.metadata:0:1
295+
hash:0:doc.epub:0:1
296+
`;
297+
globalThis.fetch = mock(
298+
createMockFetch(
299+
emptyResponse(),
300+
textResponse(file),
301+
jsonResponse({ foo: "bar" }),
302+
),
303+
);
304+
305+
const api = await remarkable("");
306+
expect(api.getContent(repHash("0"))).rejects.toThrow("\nor\n");
307+
});
289308
});
290309

291310
test("#getMetadata()", async () => {

src/index.ts

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1628,19 +1628,24 @@ class RawRemarkable implements RawRemarkableApi {
16281628
async getContent(hash: string): Promise<Content> {
16291629
const raw = await this.getText(hash);
16301630
const loaded = JSON.parse(raw) as unknown;
1631+
16311632
// jtd can't verify non-discriminated unions, in this case, we have fileType
1632-
// defined or not. As a result, we only do a normal guard for the presence
1633-
// of tags (e.g. empty content or only specify tags). Otherwise we'll throw
1634-
// the full error for the richer content.
1635-
if (collectionContent.guard(loaded)) {
1636-
return loaded;
1637-
} else if (templateContent.guard(loaded)) {
1638-
return loaded;
1639-
} else if (documentContent.guardAssert(loaded)) {
1640-
return loaded;
1641-
} else {
1642-
throw Error("invalid content");
1633+
// defined or not. As a result, we try each, and concatenate the errors at the end
1634+
const errors: string[] = [];
1635+
for (const [name, valid] of [
1636+
["collection", collectionContent],
1637+
["template", templateContent],
1638+
["document", documentContent],
1639+
] as const) {
1640+
try {
1641+
if (valid.guardAssert(loaded)) return loaded;
1642+
} catch (ex) {
1643+
const msg = ex instanceof Error ? ex.message : "unknown error type";
1644+
errors.push(`Couldn't validate as ${name} because:\n${msg}`);
1645+
}
16431646
}
1647+
const joined = errors.join("\n\nor\n\n");
1648+
throw new Error(`invalid content: ${joined}`);
16441649
}
16451650

16461651
async getMetadata(hash: string): Promise<Metadata> {

0 commit comments

Comments
 (0)