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

Error handling improvements #171

Merged
merged 2 commits into from
Apr 23, 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
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@crowdin/crowdin-api-client",
"version": "1.17.1",
"version": "1.18.0",
"description": "JavaScript library for Crowdin API v2.",
"main": "out/index.js",
"types": "out/index.d.ts",
Expand Down
82 changes: 54 additions & 28 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,6 @@ export interface Pagination {

export type PaginationOptions = Partial<Pagination>;

export interface ValidationErrorResponse {
errors: ErrorHolder[];
}

export interface CommonErrorResponse {
error: Error;
}

export interface ErrorHolder {
error: ErrorKey;
}

export interface ErrorKey {
key: string;
errors: Error[];
}

export interface Error {
code: string;
message: string;
}

export interface PatchRequest {
value?: any;
op: PatchOperation;
Expand Down Expand Up @@ -98,6 +76,44 @@ export interface Attribute {
[key: string]: string;
}

export class CrowdinError extends Error {
public code: number;
constructor(message: string, code: number) {
super(message);
this.code = code;
}
}

export class CrowdinValidationError extends CrowdinError {
public validationCodes: string[];
constructor(messsage: string, validationCodes: string[]) {
super(messsage, 400);
this.validationCodes = validationCodes;
}
}

function handleError<T>(error: any = {}): T {
if (Array.isArray(error.errors)) {
const validationCodes: string[] = [];
const validationMessages: string[] = [];
error.errors.forEach((e: any) => {
if (Array.isArray(e.error?.errors)) {
e.error.errors.forEach((er: any) => {
if (er.message && er.code) {
validationCodes.push(er.code);
validationMessages.push(er.message);
}
});
}
});
const message = validationMessages.length === 0 ? 'Validation error' : validationMessages.join(', ');
throw new CrowdinValidationError(message, validationCodes);
}
const message = error.error?.message || 'Error occured';
const code = error.error?.code || 500;
throw new CrowdinError(message, code);
}

export abstract class CrowdinApi {
private static readonly CROWDIN_URL_SUFFIX: string = 'api.crowdin.com/api/v2';
private static readonly AXIOS_INSTANCE = new AxiosProvider().axios;
Expand Down Expand Up @@ -249,27 +265,37 @@ export abstract class CrowdinApi {
//Http overrides

protected get<T>(url: string, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.get(url, config));
return this.retryService.executeAsyncFunc(() => this.httpClient.get<T>(url, config).catch(e => handleError(e)));
}

protected delete<T>(url: string, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.delete(url, config));
return this.retryService.executeAsyncFunc(() =>
this.httpClient.delete<T>(url, config).catch(e => handleError(e)),
);
}

protected head<T>(url: string, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.head(url, config));
return this.retryService.executeAsyncFunc(() =>
this.httpClient.head<T>(url, config).catch(e => handleError(e)),
);
}

protected post<T>(url: string, data?: unknown, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.post(url, data, config));
return this.retryService.executeAsyncFunc(() =>
this.httpClient.post<T>(url, data, config).catch(e => handleError(e)),
);
}

protected put<T>(url: string, data?: unknown, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.put(url, data, config));
return this.retryService.executeAsyncFunc(() =>
this.httpClient.put<T>(url, data, config).catch(e => handleError(e)),
);
}

protected patch<T>(url: string, data?: unknown, config?: { headers: Record<string, string> }): Promise<T> {
return this.retryService.executeAsyncFunc(() => this.httpClient.patch(url, data, config));
return this.retryService.executeAsyncFunc(() =>
this.httpClient.patch<T>(url, data, config).catch(e => handleError(e)),
);
}
}

Expand Down
18 changes: 1 addition & 17 deletions src/core/internal/axios/axiosProvider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import axios, { AxiosInstance } from 'axios';
import { CommonErrorResponse, ValidationErrorResponse } from '../..';

export class AxiosProvider {
private static readonly CROWDIN_API_MAX_CONCURRENT_REQUESTS = 15;
Expand Down Expand Up @@ -36,22 +35,7 @@ export class AxiosProvider {
},
error => {
this.pendingRequests = Math.max(0, this.pendingRequests - 1);
if (error.response?.data) {
if (error.response.status === 400) {
return Promise.reject(error.response.data as ValidationErrorResponse);
} else {
return Promise.reject(error.response.data as CommonErrorResponse);
}
} else {
const errorCode = error.response?.status ?? '500';
const defaultError: CommonErrorResponse = {
error: {
code: errorCode,
message: `Request failed. ${error}`,
},
};
return Promise.reject(defaultError);
}
return Promise.reject(error.response.data);
},
);
}
Expand Down