Skip to content

Commit a13ac1d

Browse files
authored
Use safeParse to correctly capture Rpc errors (#15)
1 parent 79d2774 commit a13ac1d

File tree

4 files changed

+133
-72
lines changed

4 files changed

+133
-72
lines changed

src/assessment.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@
2121
import { z } from "zod";
2222
import * as action from "./action";
2323

24+
export const ErrorSchema = z
25+
.object({
26+
code: z.number().optional(),
27+
message: z.string().optional(),
28+
status: z.number().or(z.string()).optional(),
29+
});
30+
31+
export const RpcErrorSchema = z.object({error: ErrorSchema.required()});
32+
2433
/** Zod Schema for FirewallPolicy type. */
2534
export const FirewallPolicySchema = z.object({
2635
name: z.string().optional(),
@@ -82,13 +91,7 @@ export const AssessmentSchema = z.object({
8291
.optional(),
8392
firewallPolicyAssessment: z
8493
.object({
85-
error: z
86-
.object({
87-
code: z.number().optional(),
88-
message: z.string().optional(),
89-
status: z.number().optional(),
90-
})
91-
.optional(),
94+
error: ErrorSchema.optional(),
9295
firewallPolicy: FirewallPolicySchema.optional(),
9396
})
9497
.optional(),

src/createAssessment.ts

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
*/
2020

2121
import * as action from "./action";
22-
import { Assessment, AssessmentSchema, Event, EventSchema } from "./assessment";
22+
import { Assessment, AssessmentSchema, Event, EventSchema, RpcErrorSchema } from "./assessment";
2323
import * as error from "./error";
2424
import { RecaptchaContext } from "./index";
2525

@@ -132,9 +132,15 @@ export async function callCreateAssessment(
132132
return response
133133
.json()
134134
.then((json) => {
135-
let ret = AssessmentSchema.parse(json);
136-
context.log("debug", "[rpc] createAssessment (ok)");
137-
return ret;
135+
let ret = AssessmentSchema.safeParse(json);
136+
if (ret.success && Object.keys(ret.data).length > 0) {
137+
return ret.data;
138+
}
139+
let err_ret = RpcErrorSchema.required().safeParse(json);
140+
if (err_ret.success) {
141+
throw err_ret.data.error;
142+
}
143+
throw {message: "Response does not conform to Assesment schema: " + json};
138144
})
139145
.catch((reason) => {
140146
throw new error.ParseError(

0 commit comments

Comments
 (0)