Skip to content

Commit

Permalink
refactor: Improve parseMetamaskError and add stories (#272)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben authored Jun 10, 2022
1 parent 16960e5 commit ab0d9eb
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 9 deletions.
47 changes: 38 additions & 9 deletions core/src/helpers/parseMetamaskError.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,44 @@
import truncateText from './truncateText';

const parseMetamaskError = function (errorMessage = ''): string {
const jsonFirstIndex = errorMessage.indexOf('{');
const jsonLastIndex = errorMessage.lastIndexOf('}');
try {
const jsonString = errorMessage.substring(jsonFirstIndex, jsonLastIndex + 1);
const metamaskError = JSON.parse(jsonString);
return truncateText(metamaskError?.value?.data?.message || 'unknown');
} catch {
return truncateText(errorMessage || 'unknown');
const UNKNOWN_ERROR_TEXT = 'unknown error';

const removeSpecialCharacters = function (text = '') {
return text.replace(/['\{\}\\"]/gm, '').replace(/\[.+\]/gm, '');
};

const getErrorDetails = function (errorMessage = '') {
// Get useful content between `"message":"` and `"`
const START_SYMBOLS = '"message":"';
const STOP_SYMBOLS = '"';
const jsonFirstIndex = errorMessage.indexOf(START_SYMBOLS);
if (jsonFirstIndex === -1) {
return '';
}
const messageStartIndex = jsonFirstIndex + START_SYMBOLS.length;
const messageStopIndex = errorMessage.indexOf(STOP_SYMBOLS, messageStartIndex);
const extractedContent = errorMessage.substring(messageStartIndex, messageStopIndex);
return removeSpecialCharacters(extractedContent).trim();
};

const getErrorTitle = function (errorMessage = '') {
// Get useful content before code starts
const jsonStartIndex = errorMessage.search(/[\(\{]/gm);
if (jsonStartIndex === -1) {
return '';
}
return errorMessage.substring(0, jsonStartIndex).trim();
};

const parseMetamaskError = function (errorMessage = ''): unknown {
const errorTitle = getErrorTitle(errorMessage);
if (!errorTitle) {
return truncateText(errorMessage || UNKNOWN_ERROR_TEXT);
}
const errorDetails = getErrorDetails(errorMessage);
if (!errorDetails) {
return errorTitle;
}
return `${errorDetails} (${errorTitle})`;
};

export default parseMetamaskError;
25 changes: 25 additions & 0 deletions frontend/components/parseMetamaskError.stories.js

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

0 comments on commit ab0d9eb

Please sign in to comment.