Skip to content

Commit fc20c0d

Browse files
committed
Add custom SquareError handling
1 parent 46347a5 commit fc20c0d

File tree

1 file changed

+63
-2
lines changed

1 file changed

+63
-2
lines changed

src/errors/SquareError.ts

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,17 @@
33
*/
44

55
import { toJson } from "../core/json";
6+
import { Error_, ErrorCategory as GeneratedErrorCategory, ErrorCode as GeneratedErrorCode } from "../api";
7+
8+
const fallbackError = {
9+
category: "V1_ERROR",
10+
code: "Unknown",
11+
} as SquareError.BodyError;
612

713
export class SquareError extends Error {
814
readonly statusCode?: number;
915
readonly body?: unknown;
16+
readonly errors: SquareError.BodyError[];
1017

1118
constructor({ message, statusCode, body }: { message?: string; statusCode?: number; body?: unknown }) {
1219
super(buildMessage({ message, statusCode, body }));
@@ -15,8 +22,25 @@ export class SquareError extends Error {
1522
this.statusCode = statusCode;
1623
}
1724

18-
if (body !== undefined) {
19-
this.body = body;
25+
this.body = body;
26+
if (body != null && typeof body === "object") {
27+
if ("errors" in body) {
28+
this.errors = (body as unknown as SquareErrorBody).errors ?? [fallbackError];
29+
}
30+
else {
31+
const v1Error = body as V1Error;
32+
this.errors = [
33+
{
34+
category: SquareError.ErrorCategory.V1Error,
35+
code: v1Error.type ?? SquareError.ErrorCode.Unknown,
36+
detail: v1Error.message,
37+
field: v1Error.field,
38+
}
39+
];
40+
}
41+
}
42+
else{
43+
this.errors = [fallbackError]
2044
}
2145
}
2246
}
@@ -45,3 +69,40 @@ function buildMessage({
4569

4670
return lines.join("\n");
4771
}
72+
73+
export namespace SquareError {
74+
export type BodyError = {
75+
/**
76+
* The high-level category for the error.
77+
* See [ErrorCategory](#type-errorcategory) for possible values
78+
*/
79+
category: ErrorCategory;
80+
/**
81+
* The specific code of the error.
82+
* See [ErrorCode](#type-errorcode) for possible values
83+
*/
84+
code: ErrorCode;
85+
} & Omit<Error_, "category" | "code">;
86+
87+
export type ErrorCategory = GeneratedErrorCategory | "V1_ERROR";
88+
export const ErrorCategory = {
89+
...GeneratedErrorCategory,
90+
V1Error: "V1_ERROR",
91+
} as const;
92+
93+
export type ErrorCode = GeneratedErrorCode | "Unknown" | string;
94+
export const ErrorCode = {
95+
...GeneratedErrorCode,
96+
Unknown: "Unknown",
97+
} as const;
98+
}
99+
100+
interface SquareErrorBody {
101+
errors?: SquareError.BodyError[];
102+
}
103+
104+
interface V1Error {
105+
type?: string;
106+
message: string;
107+
field: string;
108+
}

0 commit comments

Comments
 (0)