Unclear error handling on failed pattern creation
Description
When a REST request for creating a pattern from the block editor returns an error the UI feedback isn't useful but just a raw JS error.
Step-by-step reproduction instructions
- Add a simple plugin that errors on pattern creation via REST API (see below).
- Open the post editor and create any block.
- Turn it into a pattern and see the error as a snackbar notice
can't access property "wp_pattern_sync_status", u is undefined
- You're back at the editor without a pattern and without any feedback understandable to the user. The error message from the REST request isn't passed through.
If you do the same with a post (changing the hook name to rest_pre_insert_post) the error message is displayed on save offering the possibility to supply the user with more useful feedback about what failed and why.
The problem seems to be that when creating a pattern any response is treated as success:
https://github.com/WordPress/gutenberg/blob/ab9bf1097299a550ca69849fd73b24f9bb8db128/packages/patterns/src/components/create-pattern-modal.jsx#L80-L89
That then always triggers the success message
https://github.com/WordPress/gutenberg/blob/20d41ae5974df4efc3daa72134790037d361b577/packages/patterns/src/components/pattern-convert-button.jsx#L119-L161
which then runs into the above error here:
https://github.com/WordPress/gutenberg/blob/20d41ae5974df4efc3daa72134790037d361b577/packages/patterns/src/components/pattern-convert-button.jsx#L120
Screenshots, screen recording, code snippet
Simple code snippet to trigger the above situation.
add_action('rest_pre_insert_wp_block', function(){
return new WP_Error(
'rest_invalid_param',
'My Error',
[ 'status' => 400 ]
);
}, 10, 0);
Environment info
WP 7.1.3
Please confirm that you have searched existing issues in the repo.
- [x] Yes
Please confirm that you have tested with all plugins deactivated except Gutenberg.
- [x] Yes
Please confirm which theme type you used for testing.
- [x] Block
- [ ] Classic
- [x] Hybrid (e.g. classic with theme.json)
- [ ] Not sure
I was able to reproduce this locally. When pattern creation fails, the snackbar shows a JavaScript error related to wp_pattern_sync_status instead of the original REST API error.
I tested adding { throwOnError: true } to saveEntityRecord in createPattern, and it now displays the original REST API error message correctly.
const updatedRecord = await registry
.dispatch( coreStore )
.saveEntityRecord( 'postType', 'wp_block', reusableBlock, {
throwOnError: true,
} );