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

51 lines
1.3 KiB
TypeScript
Raw Normal View History

import { Dictionary } from "farmbot";
import { t } from "i18next";
import * as _ from "lodash";
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."
const reason = _.capitalize(("" + k).split("_").join(" "));
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);
return _.map(errors, mapper).join(" ");
}
function safelyFetchErrors(err: AxiosErrorResponse): Dictionary<string> {
// In case the interpreter gives us an oddball error message.
if (err && err.response && err.response.data) {
return err.response.data;
} else {
return {
error: t("Your web browser is unable to communicate with the " +
"web app server. Make sure you are connected to the Internet.")
};
}
}
export function bail(message: string): never {
throw new Error(message);
}
export const catchErrors = (error: Error) => {
2018-03-19 09:25:42 -06:00
if (window.Rollbar && window.Rollbar.error) {
window.Rollbar.error(error);
2018-01-20 10:23:26 -07:00
} else {
throw error;
}
};