@bit-ui-libs/common
Version:
This library was generated with [Nx](https://nx.dev).
74 lines (64 loc) • 2.72 kB
text/typescript
import axios from 'axios';
import { ApiServiceError } from '../../api/interfaces/api-service-error';
/**
* This is a no-man's land function that tries
* to handle every possible error scenario from ChainIT frontend & backend.
* Handles simple error messages, axios errors, and now FATAL server error objects
*/
export function getErrorMessage(err: unknown) {
if (!err) return '';
// First, check if the error is an Axios error
if (axios.isAxiosError(err) || (err as any)?.response) {
const axiosError = err as ApiServiceError;
// If response.data.message is not available then check for message
const message = axiosError.response?.data?.message;
// Backend returns an error message
if (typeof message === 'string') {
return message;
}
// Backend returns a really bad internal server error object
// (e.g. { query: "UPDATE ...", parameters: [...], driverError: {...} })
else if (typeof message === 'object') {
// Usually, backend returns message as string array with the errors... usually.
if (Array.isArray(message) && (message as any[]).every(m => typeof m === 'string')) {
return (message as string[]).join(', ');
}
let fatalErrorMessage = JSON.stringify(message);
// If the message comes as an object,
// there is usually error details in a neighboring "error" property.
const details = (axiosError.response?.data as any)?.error;
// Prepend to fatal error object
if (details) fatalErrorMessage = details + fatalErrorMessage;
// Returns the error details + fatal error object
return fatalErrorMessage;
}
// If none of the above work try accessing first-level message
else if (axiosError.message) {
return axiosError.message;
}
// This error isn't an axios error,
// start checking for other properties below.
}
// Second, check if the error is an RTK error
if (err && typeof err === 'object' && 'status' in err && 'data' in err) {
if (Object.prototype.hasOwnProperty.call(err.data, 'message')) {
return (err.data as { message: string }).message;
}
}
// Next, check if the error is of type Error
if (err instanceof Error) {
const error = err as Error;
return error.message;
}
// Next, check if the error has a property called message
// (it can have message but not be of type Error (e.g. Geolocation error))
if (Object.prototype.hasOwnProperty.call(err, 'message')) {
return (err as { message: string }).message;
}
// Next, check if the error is just a string
if (typeof err === 'string') {
return err;
}
// Last resort, return a hardcoded unknown error message
return 'Unknown error';
}