Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(connector): connector error handler, throw errmsg on general errors #1458

Merged
merged 10 commits into from
Jul 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/connector-alipay-native/src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ export const alipaySigningAlgorithmMapping = {
} as const;
export const alipaySigningAlgorithms = ['RSA', 'RSA2'] as const;

export const invalidAccessTokenCode = ['20001'];

export const invalidAccessTokenSubCode = ['isv.code-invalid'];

export const defaultMetadata: ConnectorMetadata = {
id: 'alipay-native',
target: 'alipay',
Expand Down
7 changes: 6 additions & 1 deletion packages/connector-alipay-native/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,12 @@ describe('getUserInfo', () => {
});

await expect(alipayNativeMethods.getUserInfo({ auth_code: 'wrong_code' })).rejects.toMatchError(
new ConnectorError(ConnectorErrorCodes.General, 'Invalid parameter')
new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: 'Invalid parameter',
code: '40002',
darcyYe marked this conversation as resolved.
Show resolved Hide resolved
sub_code: 'isv.invalid-parameter',
sub_msg: '参数无效',
})
);
});

Expand Down
43 changes: 26 additions & 17 deletions packages/connector-alipay-native/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {
defaultMetadata,
defaultTimeout,
timestampFormat,
invalidAccessTokenCode,
invalidAccessTokenSubCode,
} from './constant';
import {
alipayNativeConfigGuard,
Expand Down Expand Up @@ -139,28 +141,35 @@ export default class AlipayNativeConnector implements SocialConnector {

const { alipay_user_info_share_response } = result.data;

const {
user_id: id,
avatar,
nick_name: name,
code,
msg,
sub_code,
} = alipay_user_info_share_response;
this.errorHandler(alipay_user_info_share_response);

const { user_id: id, avatar, nick_name: name } = alipay_user_info_share_response;

this.errorHandler({ code, msg, sub_code });
assert(id, new ConnectorError(ConnectorErrorCodes.InvalidResponse));
if (!id) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse);
}

return { id, avatar, name };
};

private readonly errorHandler: ErrorHandler = ({ code, msg, sub_code }) => {
assert(code !== '20001', new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid, msg));
assert(
sub_code !== 'isv.code-invalid',
new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid, msg)
);
assert(!sub_code, new ConnectorError(ConnectorErrorCodes.General, msg));
private readonly errorHandler: ErrorHandler = ({ code, msg, sub_code, sub_msg }) => {
if (invalidAccessTokenCode.includes(code)) {
throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid, msg);
}

if (sub_code) {
assert(
!invalidAccessTokenSubCode.includes(sub_code),
new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid, msg)
);

throw new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: msg,
code,
sub_code,
sub_msg,
});
}
};

private readonly authorizationCallbackHandler = async (parameterObject: unknown) => {
Expand Down
9 changes: 3 additions & 6 deletions packages/connector-alipay-native/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,13 @@ export const alipayUserInfoShareResponseGuard = z.object({
sub_msg: z.string().optional(),
});

type AlipayUserInfoShareResponseGuard = z.infer<typeof alipayUserInfoShareResponseGuard>;

export const userInfoResponseGuard = z.object({
sign: z.string(), // To know `sign` details, see: https://opendocs.alipay.com/common/02kf5q
alipay_user_info_share_response: alipayUserInfoShareResponseGuard,
});

export type UserInfoResponse = z.infer<typeof userInfoResponseGuard>;

export type ErrorHandler = (response: {
code: string;
msg: string;
sub_code?: string;
sub_msg?: string;
}) => void;
export type ErrorHandler = (response: AlipayUserInfoShareResponseGuard) => void;
4 changes: 4 additions & 0 deletions packages/connector-alipay/src/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ export const alipaySigningAlgorithms = ['RSA', 'RSA2'] as const;
export const charsetEnum = ['GBK', 'UTF8'] as const;
export const fallbackCharset = 'UTF8';

export const invalidAccessTokenCode = ['20001'];

export const invalidAccessTokenSubCode = ['isv.code-invalid'];

export const defaultMetadata: ConnectorMetadata = {
id: 'alipay-web',
target: 'alipay',
Expand Down
9 changes: 7 additions & 2 deletions packages/connector-alipay/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ describe('getUserInfo', () => {

it('throw General error if auth_code not provided in input', async () => {
await expect(alipayMethods.getUserInfo({})).rejects.toMatchError(
new ConnectorError(ConnectorErrorCodes.General, '{}')
new ConnectorError(ConnectorErrorCodes.InvalidResponse, '{}')
);
});

Expand Down Expand Up @@ -216,7 +216,12 @@ describe('getUserInfo', () => {
});

await expect(alipayMethods.getUserInfo({ auth_code: 'wrong_code' })).rejects.toMatchError(
new ConnectorError(ConnectorErrorCodes.General, 'Invalid parameter')
new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: 'Invalid parameter',
code: '40002',
sub_code: 'isv.invalid-parameter',
sub_msg: '参数无效',
})
);
});

Expand Down
52 changes: 33 additions & 19 deletions packages/connector-alipay/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {
defaultTimeout,
timestampFormat,
fallbackCharset,
invalidAccessTokenCode,
invalidAccessTokenSubCode,
} from './constant';
import {
alipayConfigGuard,
Expand Down Expand Up @@ -140,36 +142,45 @@ export default class AlipayConnector implements SocialConnector {
timeout: defaultTimeout,
});

const result = userInfoResponseGuard.safeParse(JSON.parse(httpResponse.body));
const { body: rawBody } = httpResponse;

const result = userInfoResponseGuard.safeParse(JSON.parse(rawBody));

if (!result.success) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error.message);
}

const { alipay_user_info_share_response } = result.data;

const {
user_id: id,
avatar,
nick_name: name,
code,
msg,
sub_code,
} = alipay_user_info_share_response;
this.errorHandler(alipay_user_info_share_response);

this.errorHandler({ code, msg, sub_code });
assert(id, new ConnectorError(ConnectorErrorCodes.InvalidResponse));
const { user_id: id, avatar, nick_name: name } = alipay_user_info_share_response;

if (!id) {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse);
}

return { id, avatar, name };
};

private readonly errorHandler: ErrorHandler = ({ code, msg, sub_code }) => {
assert(code !== '20001', new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid, msg));
assert(
sub_code !== 'isv.code-invalid',
new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid, msg)
);
assert(!sub_code, new ConnectorError(ConnectorErrorCodes.General, msg));
private readonly errorHandler: ErrorHandler = ({ code, msg, sub_code, sub_msg }) => {
if (invalidAccessTokenCode.includes(code)) {
throw new ConnectorError(ConnectorErrorCodes.SocialAccessTokenInvalid, msg);
}

if (sub_code) {
assert(
!invalidAccessTokenSubCode.includes(sub_code),
new ConnectorError(ConnectorErrorCodes.SocialAuthCodeInvalid, msg)
);

throw new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: msg,
code,
sub_code,
sub_msg,
});
}
};

private readonly authorizationCallbackHandler = async (parameterObject: unknown) => {
Expand All @@ -178,7 +189,10 @@ export default class AlipayConnector implements SocialConnector {
const result = dataGuard.safeParse(parameterObject);

if (!result.success) {
throw new ConnectorError(ConnectorErrorCodes.General, JSON.stringify(parameterObject));
throw new ConnectorError(
ConnectorErrorCodes.InvalidResponse,
JSON.stringify(parameterObject)
);
}

return result.data;
Expand Down
9 changes: 3 additions & 6 deletions packages/connector-alipay/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,13 @@ export const alipayUserInfoShareResponseGuard = z.object({
sub_msg: z.string().optional(),
});

type AlipayUserInfoShareResponse = z.infer<typeof alipayUserInfoShareResponseGuard>;

export const userInfoResponseGuard = z.object({
sign: z.string(), // To know `sign` details, see: https://opendocs.alipay.com/common/02kf5q
alipay_user_info_share_response: alipayUserInfoShareResponseGuard,
});

export type UserInfoResponse = z.infer<typeof userInfoResponseGuard>;

export type ErrorHandler = (response: {
code: string;
msg: string;
sub_code?: string;
sub_msg?: string;
}) => void;
export type ErrorHandler = (response: AlipayUserInfoShareResponse) => void;
16 changes: 4 additions & 12 deletions packages/connector-aliyun-dm/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,13 @@ export default class AliyunDmConnector implements EmailConnector {
const {
response: { body: rawBody },
} = error;

assert(
typeof rawBody === 'string',
new ConnectorError(ConnectorErrorCodes.InvalidResponse)
);

this.errorHandler(rawBody);
throw new ConnectorError(ConnectorErrorCodes.General, rawBody);
}

throw error;
Expand All @@ -97,17 +98,8 @@ export default class AliyunDmConnector implements EmailConnector {
throw new ConnectorError(ConnectorErrorCodes.InvalidResponse, result.error.message);
}

const { Code } = result.data;
const { Message: errorDescription, ...rest } = result.data;

// See https://help.aliyun.com/document_detail/29444.html.
assert(
!(
Code === 'InvalidBody' ||
Code === 'InvalidTemplate.NotFound' ||
Code === 'InvalidSubject.Malformed' ||
Code === 'InvalidFromAlias.Malformed'
),
new ConnectorError(ConnectorErrorCodes.InvalidConfig, errorResponseBody)
);
throw new ConnectorError(ConnectorErrorCodes.General, { errorDescription, ...rest });
};
}
1 change: 1 addition & 0 deletions packages/connector-aliyun-dm/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export const sendMailErrorResponseGuard = z.object({
Message: z.string(),
RequestId: z.string().optional(),
HostId: z.string().optional(),
Recommend: z.string().optional(),
});

export type SendMailErrorResponse = z.infer<typeof sendMailErrorResponseGuard>;
30 changes: 12 additions & 18 deletions packages/connector-aliyun-sms/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ export default class AliyunSmsConnector implements SmsConnector {
}
};

/* eslint-disable complexity */
public sendMessage: SmsSendMessageFunction = async (phone, type, { code }, config) => {
const smsConfig =
(config as AliyunSmsConfig | undefined) ?? (await this.getConfig(this.metadata.id));
Expand All @@ -54,14 +53,14 @@ export default class AliyunSmsConnector implements SmsConnector {

const { body: rawBody } = httpResponse;

const { Code } = this.parseResponseString(rawBody);

if (Code === 'isv.ACCOUNT_NOT_EXISTS' || Code === 'isv.SMS_TEMPLATE_ILLEGAL') {
throw new ConnectorError(ConnectorErrorCodes.InvalidConfig, rawBody);
}
const { Code, Message, ...rest } = this.parseResponseString(rawBody);

if (Code !== 'OK') {
throw new ConnectorError(ConnectorErrorCodes.General, rawBody);
throw new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: Message,
Code,
...rest,
});
}

return httpResponse;
Expand All @@ -76,20 +75,15 @@ export default class AliyunSmsConnector implements SmsConnector {

assert(typeof rawBody === 'string', new ConnectorError(ConnectorErrorCodes.InvalidResponse));

const { Code } = this.parseResponseString(rawBody);

if (Code.includes('InvalidAccessKeyId')) {
throw new ConnectorError(ConnectorErrorCodes.InvalidConfig, rawBody);
}

if (Code === 'SignatureDoesNotMatch' || Code === 'IncompleteSignature') {
throw new ConnectorError(ConnectorErrorCodes.InvalidConfig, rawBody);
}
const { Code, Message, ...rest } = this.parseResponseString(rawBody);

throw new ConnectorError(ConnectorErrorCodes.General, rawBody);
throw new ConnectorError(ConnectorErrorCodes.General, {
errorDescription: Message,
Code,
...rest,
});
}
};
/* eslint-enable complexity */

private readonly parseResponseString = (response: string) => {
const result = sendSmsResponseGuard.safeParse(JSON.parse(response));
Expand Down
10 changes: 6 additions & 4 deletions packages/connector-facebook/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,10 +194,12 @@ describe('facebook connector', () => {
error_reason: 'user_denied',
})
).rejects.toMatchError(
new ConnectorError(
ConnectorErrorCodes.General,
'{"error":"general_error","error_code":200,"error_description":"General error encountered.","error_reason":"user_denied"}'
)
new ConnectorError(ConnectorErrorCodes.General, {
error: 'general_error',
error_code: 200,
errorDescription: 'General error encountered.',
error_reason: 'user_denied',
})
);
});

Expand Down
Loading