2020-12-17 14:52:44 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { __ } from '@wordpress/i18n';
|
2022-04-11 12:11:25 +00:00
|
|
|
import { decodeEntities } from '@wordpress/html-entities';
|
2020-12-17 14:52:44 +00:00
|
|
|
|
2019-09-04 16:07:00 +00:00
|
|
|
/**
|
2022-09-20 15:54:25 +00:00
|
|
|
* Given a JS error or a fetch response error, parse and format it, so it can be displayed to the user.
|
2019-09-04 16:07:00 +00:00
|
|
|
*
|
2022-04-08 13:47:19 +00:00
|
|
|
* @param {Object} error Error object.
|
|
|
|
* @param {Function} [error.json] If a json method is specified, it will try parsing the error first.
|
|
|
|
* @param {string} [error.message] If a message is specified, it will be shown to the user.
|
|
|
|
* @param {string} [error.type] The context in which the error was triggered.
|
2021-08-06 13:25:12 +00:00
|
|
|
* @return {Promise<{message:string;type:string;}>} Error object containing a message and type.
|
2019-09-04 16:07:00 +00:00
|
|
|
*/
|
|
|
|
export const formatError = async ( error ) => {
|
|
|
|
if ( typeof error.json === 'function' ) {
|
|
|
|
try {
|
|
|
|
const parsedError = await error.json();
|
|
|
|
return {
|
|
|
|
message: parsedError.message,
|
|
|
|
type: parsedError.type || 'api',
|
|
|
|
};
|
|
|
|
} catch ( e ) {
|
|
|
|
return {
|
|
|
|
message: e.message,
|
|
|
|
type: 'general',
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
message: error.message,
|
|
|
|
type: error.type || 'general',
|
2019-08-30 09:36:06 +00:00
|
|
|
};
|
|
|
|
};
|
2020-12-17 14:52:44 +00:00
|
|
|
|
|
|
|
/**
|
2022-09-20 15:54:25 +00:00
|
|
|
* Given an API response object, formats the error message into something more human-readable.
|
2020-12-17 14:52:44 +00:00
|
|
|
*
|
2022-04-08 13:47:19 +00:00
|
|
|
* @param {Object} response Response object.
|
2020-12-17 14:52:44 +00:00
|
|
|
* @return {string} Error message.
|
|
|
|
*/
|
|
|
|
export const formatStoreApiErrorMessage = ( response ) => {
|
|
|
|
if ( response.data && response.code === 'rest_invalid_param' ) {
|
|
|
|
const invalidParams = Object.values( response.data.params );
|
|
|
|
if ( invalidParams[ 0 ] ) {
|
|
|
|
return invalidParams[ 0 ];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-20 15:54:25 +00:00
|
|
|
if ( ! response?.message ) {
|
|
|
|
return __(
|
|
|
|
'Something went wrong. Please contact us to get assistance.',
|
|
|
|
'woo-gutenberg-products-block'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
return decodeEntities( response.message );
|
2020-12-17 14:52:44 +00:00
|
|
|
};
|