diff --git a/packages/core-data/CHANGELOG.md b/packages/core-data/CHANGELOG.md index a3a686d117a10e..27ec2a9c231d26 100644 --- a/packages/core-data/CHANGELOG.md +++ b/packages/core-data/CHANGELOG.md @@ -2,6 +2,10 @@ ## Unreleased +### Enhancements + +- Improve error reporting in private action `saveDirtyEntities` ([#81151](https://github.com/WordPress/gutenberg/pull/81151)). + ### Bug Fixes - Ensure revision resolvers finish after fetched revisions are stored. diff --git a/packages/core-data/src/private-actions.js b/packages/core-data/src/private-actions.js index 668c61d51fa059..acf10a4599a34a 100644 --- a/packages/core-data/src/private-actions.js +++ b/packages/core-data/src/private-actions.js @@ -4,6 +4,7 @@ import apiFetch from '@wordpress/api-fetch'; import { store as noticesStore } from '@wordpress/notices'; import { store as blockEditorStore } from '@wordpress/block-editor'; +import { decodeEntities } from '@wordpress/html-entities'; import { __ } from '@wordpress/i18n'; /** @@ -313,7 +314,10 @@ export const saveDirtyEntities = pendingSavedRecords.push( registry .dispatch( STORE_NAME ) - .saveEditedEntityRecord( kind, name, key ) + .saveEditedEntityRecord( kind, name, key, { + throwOnError: true, + } ) + .catch( ensureError ) ); } } ); @@ -325,15 +329,19 @@ export const saveDirtyEntities = 'root', 'site', undefined, - siteItemsToSave + siteItemsToSave, + { + throwOnError: true, + } ) + .catch( ensureError ) ); } registry .dispatch( blockEditorStore ) .__unstableMarkLastChangeAsPersistent(); - Promise.all( pendingSavedRecords ) + return Promise.all( pendingSavedRecords ) .then( async ( values ) => { if ( onSave ) { await onSave(); @@ -341,12 +349,23 @@ export const saveDirtyEntities = return values; } ) .then( ( values ) => { - if ( - values.some( ( value ) => typeof value === 'undefined' ) - ) { + const errors = values.filter( ( v ) => v instanceof Error ); + if ( errors.length ) { + const firstMessage = errors.find( + ( e ) => e.message + )?.message; + registry .dispatch( noticesStore ) - .createErrorNotice( __( 'Saving failed.' ) ); + .createErrorNotice( + decodeEntities( + firstMessage || __( 'Saving failed.' ) + ), + { + type: 'snackbar', + id: saveNoticeId, + } + ); } else { registry .dispatch( noticesStore ) @@ -370,7 +389,43 @@ export const saveDirtyEntities = registry .dispatch( noticesStore ) .createErrorNotice( - `${ __( 'Saving failed.' ) } ${ error }` + decodeEntities( + error?.message || __( 'Saving failed.' ) + ), + { + type: 'snackbar', + id: saveNoticeId, + } ) ); + + function ensureError( error ) { + if ( error instanceof Error ) { + return error; + } + + // Expect certain errors to be plain objects with a `message` + // property, such as those thrown by `apiFetch`. Otherwise, do our + // best to infer a message via duck typing. + let message; + if ( ! error ) { + } else if ( typeof error.message === 'string' ) { + message = error.message; + } else if ( typeof error === 'string' ) { + message = error; + } else if ( + // Only consider own method, lest we erroneously end up calling + // `Object#toString` at the end of the prototype chain, thereby + // returning `"[object Object]"`. + Object.hasOwn( error, 'toString' ) && + typeof error.toString === 'function' + ) { + const result = error.toString(); + if ( typeof result === 'string' ) { + message = result; + } + } + + return new Error( message, { cause: error } ); + } }; diff --git a/packages/core-data/src/test/private-actions.js b/packages/core-data/src/test/private-actions.js index ab1ed37bb44951..75e1dc187f76ac 100644 --- a/packages/core-data/src/test/private-actions.js +++ b/packages/core-data/src/test/private-actions.js @@ -2,12 +2,17 @@ * WordPress dependencies */ import apiFetch from '@wordpress/api-fetch'; +import { store as blockEditorStore } from '@wordpress/block-editor'; +import { createRegistry } from '@wordpress/data'; +import { store as noticesStore } from '@wordpress/notices'; /** * Internal dependencies */ +import { store as coreStore } from '..'; import { editMediaEntity, setCollaborationSupported } from '../private-actions'; import { getSyncManager, hasSyncManager } from '../sync'; +import { unlock } from '../lock-unlock'; jest.mock( '@wordpress/api-fetch' ); jest.mock( '../sync', () => ( { @@ -248,3 +253,295 @@ describe( 'setCollaborationSupported', () => { } ); } ); } ); + +describe( 'saveDirtyEntities', () => { + beforeEach( () => { + apiFetch.mockReset(); + } ); + + const postTypeConfig = { + kind: 'postType', + name: 'post', + baseURL: '/wp/v2/posts', + transientEdits: { blocks: true, selection: true }, + mergedEdits: { meta: true }, + }; + + const postId = 44; + + const post = { + id: postId, + type: 'post', + title: 'bar', + content: 'bar', + excerpt: 'crackers', + status: 'draft', + }; + + const postEntityRecord = { + key: postId, + kind: 'postType', + name: 'post', + title: 'bar', + }; + + function createRegistryWithStoresAndEditedPost() { + const registry = createRegistry(); + + registry.register( blockEditorStore ); + registry.register( coreStore ); + registry.register( noticesStore ); + + registry.dispatch( coreStore ).addEntities( [ postTypeConfig ] ); + + registry + .dispatch( coreStore ) + .receiveEntityRecords( 'postType', 'post', post ); + + registry + .dispatch( coreStore ) + .editEntityRecord( 'postType', 'post', postId, { + content: 'new bar', + } ); + + return registry; + } + + const hasEdits = ( registry ) => + registry + .select( coreStore ) + .hasEditsForEntityRecord( 'postType', 'post', postId ); + + const getContent = ( registry ) => + registry + .select( coreStore ) + .getEditedEntityRecord( 'postType', 'post', postId ).content; + + const getMethod = ( options ) => + options.headers?.[ 'X-HTTP-Method-Override' ] || + options.method || + 'GET'; + + it( 'saves modified entities', async () => { + apiFetch.mockImplementation( async ( options ) => { + const method = getMethod( options ); + const { path, data } = options; + + if ( + method === 'PUT' && + path.startsWith( `/wp/v2/posts/${ postId }` ) + ) { + return { ...post, ...data }; + } + + throw { + code: 'unknown_path', + message: `Unknown path: ${ method } ${ path }`, + }; + } ); + + const registry = createRegistryWithStoresAndEditedPost(); + + expect( hasEdits( registry ) ).toBe( true ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( getContent( registry ) ).toBe( 'new bar' ); + expect( hasEdits( registry ) ).toBe( false ); + + const notices = registry.select( noticesStore ).getNotices(); + expect( notices ).toMatchObject( [ + { + status: 'success', + content: 'Site updated.', + }, + ] ); + } ); + + it( 'shows a notice to convey errors', async () => { + apiFetch.mockImplementation( async ( options ) => { + const method = getMethod( options ); + const { path } = options; + + throw { + code: 'unknown_path', + message: `Unknown path: ${ method } ${ path }`, + }; + } ); + + const registry = createRegistryWithStoresAndEditedPost(); + + expect( hasEdits( registry ) ).toBe( true ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( getContent( registry ) ).toBe( 'new bar' ); + expect( hasEdits( registry ) ).toBe( true ); + + const notices = registry.select( noticesStore ).getNotices(); + expect( notices[ 0 ].status ).toBe( 'error' ); + expect( notices[ 0 ].content ).toMatch( /^Unknown path/ ); + } ); + + it( 'derives error messages depending on failure scenario', async () => { + const registry = createRegistryWithStoresAndEditedPost(); + + // Throw an object with a `message` property + apiFetch.mockImplementation( async () => { + throw { + message: 'Lorem ipsum', + }; + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Lorem ipsum', + } ); + + // Throw an object with an empty `message` property + apiFetch.mockImplementation( async () => { + throw { + message: '', + }; + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Saving failed.', + } ); + + // Throw an actual error + apiFetch.mockImplementation( async () => { + throw new Error( 'Dolor sit amet' ); + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Dolor sit amet', + } ); + + // Throw a string + apiFetch.mockImplementation( async () => { + throw 'Consectetur adipiscing elit'; + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Consectetur adipiscing elit', + } ); + + // Throw an object implementing `toString` + apiFetch.mockImplementation( async () => { + throw { + toString() { + return 'Sed do eiusmod tempor incididunt'; + }, + }; + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Sed do eiusmod tempor incididunt', + } ); + + // Throw something with no clear message + apiFetch.mockImplementation( async () => { + throw {}; + } ); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + } ); + + expect( + registry.select( noticesStore ).getNotices().at( -1 ) + ).toMatchObject( { + status: 'error', + content: 'Saving failed.', + } ); + } ); + + it( 'aborts if `onSave` fails', async () => { + apiFetch.mockImplementation( async () => { + throw { + code: 'unknown_path', + message: 'Unknown path', + }; + } ); + + const registry = createRegistryWithStoresAndEditedPost(); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + async onSave() { + throw new Error( 'oh no' ); + }, + } ); + + expect( hasEdits( registry ) ).toBe( true ); + + const notices = registry.select( noticesStore ).getNotices(); + expect( notices ).toMatchObject( [ + { + status: 'error', + content: 'oh no', + }, + ] ); + } ); + + it( 'honors the `successNoticeContent` prop', async () => { + apiFetch.mockImplementation( async ( options ) => { + const { data } = options; + return { ...post, ...data }; + } ); + + const registry = createRegistryWithStoresAndEditedPost(); + + await unlock( registry.dispatch( coreStore ) ).saveDirtyEntities( { + dirtyEntityRecords: [ postEntityRecord ], + successNoticeContent: 'eureka', + } ); + + const notices = registry.select( noticesStore ).getNotices(); + expect( notices ).toMatchObject( [ + { + status: 'success', + content: 'eureka', + }, + ] ); + } ); +} );