Index: src/wp-includes/rest-api.php
===================================================================
--- src/wp-includes/rest-api.php	(revision 45273)
+++ src/wp-includes/rest-api.php	(working copy)
@@ -179,6 +179,7 @@
 
 	// Default serving.
 	add_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
+	add_filter( 'rest_pre_serve_request', 'rest_add_wp_die_handler_filter', 10 );
 	add_filter( 'rest_post_dispatch', 'rest_send_allow_header', 10, 3 );
 	add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
 
@@ -646,6 +647,29 @@
 }
 
 /**
+ * Add the filter for the custom wp_die handler.
+ *
+ * This is hooked on rest_pre_dispatch, so any uses of wp_die in endpoints
+ * will be wrapped by our custom wp_die handler to output JSON rather than the
+ * usual HTML error page.
+ *
+ * @since 5.3.0
+ */
+function rest_add_wp_die_handler_filter() {
+	add_filter( 'wp_die_handler', 'rest_wp_die_handler_callback' );
+}
+
+/**
+ * Callback to set the wp_die handler to rest_wp_die_handler.
+ *
+ * @return string
+ * @since 5.3.0
+ */
+function rest_wp_die_handler_callback() {
+	return '_json_wp_die_handler';
+}
+
+/**
  * Sends the "Allow" header to state all methods that can be sent to the current route.
  *
  * @since 4.4.0
