Farmbot-Web-App/frontend/util/errors.ts

51 lines
1.2 KiB
TypeScript
Raw Normal View History

import { Dictionary } from "farmbot";
2018-11-29 12:54:53 -07:00
import { Content } from "../constants";
2019-02-04 07:32:26 -07:00
import { capitalize, map } from "lodash";
2019-04-02 13:59:37 -06:00
import { t } from "../i18next_wrapper";
export interface AxiosErrorResponse {
response?: {
data: {
[reason: string]: string
};
};
}
2018-04-17 07:44:47 -06:00
const mapper = (v: string, k: string) => {
// "Reason: Explanation lorem ipsum dolor ipsum."
2019-02-04 07:32:26 -07:00
const reason = capitalize(("" + k).split("_").join(" "));
2018-04-17 07:44:47 -06:00
const explanation = v.toString();
2018-05-12 09:01:29 -06:00
return t(`${reason}: ${explanation}`);
2018-04-17 07:44:47 -06:00
};
/** Concats and capitalizes all of the error key/value
* pairs returned by the /api/xyz endpoint. */
export function prettyPrintApiErrors(err: AxiosErrorResponse) {
2018-04-17 07:44:47 -06:00
const errors = safelyFetchErrors(err);
2019-02-04 07:32:26 -07:00
return map(errors, mapper).join(" ");
}
function safelyFetchErrors(err: AxiosErrorResponse): Dictionary<string> {
// In case the interpreter gives us an oddball error message.
2020-01-03 13:04:45 -07:00
if (err.response?.data) {
return err.response.data;
} else {
return {
2018-11-29 12:54:53 -07:00
error: t(Content.WEB_APP_DISCONNECTED)
};
}
}
export function bail(message: string): never {
throw new Error(message);
}
export const catchErrors = (error: Error) => {
2020-01-03 13:04:45 -07:00
if (window.Rollbar?.error) {
2018-03-19 09:25:42 -06:00
window.Rollbar.error(error);
2018-01-20 10:23:26 -07:00
} else {
throw error;
}
};