Skip to content

Commit

Permalink
Improve error handling on UI
Browse files Browse the repository at this point in the history
  • Loading branch information
LASER-Yi committed Jun 14, 2022
1 parent 4640bad commit c3645c9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 12 deletions.
46 changes: 34 additions & 12 deletions frontend/src/apis/queries/client.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import SocketIO from "@/modules/socketio";
import { notification } from "@/modules/task";
import { LOG } from "@/utilities/console";
import { setLoginRequired } from "@/utilities/event";
import { showNotification } from "@mantine/notifications";
import Axios, { AxiosError, AxiosInstance, CancelTokenSource } from "axios";
import { Environment } from "../../utilities";

function GetErrorMessage(data: unknown, defaultMsg = "Unknown error"): string {
if (typeof data === "string") {
return data;
} else {
return defaultMsg;
}
}

class BazarrClient {
axios!: AxiosInstance;
source!: CancelTokenSource;
Expand Down Expand Up @@ -36,32 +47,43 @@ class BazarrClient {
if (resp.status >= 200 && resp.status < 300) {
return Promise.resolve(resp);
} else {
this.handleError(resp.status);
const error: BackendError = {
code: resp.status,
message: GetErrorMessage(resp.data),
};
this.handleError(error);
return Promise.reject(resp);
}
},
(error: AxiosError) => {
if (error.response) {
const response = error.response;
this.handleError(response.status);
} else {
error.message = "You have disconnected to Bazarr backend";
}
const message = GetErrorMessage(
error.response?.data,
"You have disconnected from the server"
);

const backendError: BackendError = {
code: error.response?.status ?? 500,
message,
};

error.message = backendError.message;
this.handleError(backendError);

return Promise.reject(error);
}
);
}

handleError(code: number) {
handleError(error: BackendError) {
const { code, message } = error;
switch (code) {
case 401:
setLoginRequired();
break;
case 500:
break;
default:
break;
}
LOG("error", "A error has occurred", code);

showNotification(notification.error(`Error ${code}`, message));
}
}

Expand Down
9 changes: 9 additions & 0 deletions frontend/src/modules/task/notification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ export const notification = {
};
},

error: (title: string, message: string): NotificationProps => {
return {
title,
message,
color: "red",
autoClose: 7 * 1000,
};
},

PROGRESS_TIMEOUT: 10 * 1000,

progress: {
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/types/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,8 @@ type ItemSearchResult = Partial<SeriesIdType> &
title: string;
year: string;
};

type BackendError = {
code: number;
message: string;
};

0 comments on commit c3645c9

Please sign in to comment.