8
0
Просмотр исходного кода

Improved restoring component if editor.getData() throws an error.

Maciej Bukowski 6 лет назад
Родитель
Сommit
66bc450218

+ 11 - 10
packages/ckeditor5-watchdog/src/watchdog.js

@@ -135,14 +135,7 @@ export default class Watchdog {
 	 * @returns {Promise.<module:core/editor/editor~Editor>}
 	 */
 	restart() {
-		try {
-			this._throttledSave.flush();
-		} catch ( err ) {
-			console.error(
-				'An error happened during restoring editor data. ' +
-				'Editor will be restored from the previously saved data.'
-			);
-		}
+		this._throttledSave.flush();
 
 		return Promise.resolve()
 			.then( () => this.destroy() )
@@ -239,8 +232,16 @@ export default class Watchdog {
 			return;
 		}
 
-		this._lastDocumentVersion = version;
-		this._data = this._editor.getData();
+		try {
+			this._data = this._editor.getData();
+			this._lastDocumentVersion = version;
+		} catch ( err ) {
+			console.error(
+				err,
+				'An error happened during restoring editor data. ' +
+				'Editor will be restored from the previously saved data.'
+			);
+		}
 	}
 
 	/**

+ 38 - 1
packages/ckeditor5-watchdog/tests/watchdog.js

@@ -527,7 +527,6 @@ describe( 'Watchdog', () => {
 					watchdog.on( 'restart', () => {
 						window.onerror = originalErrorHandler;
 
-						console.log( watchdog.editor.getData() );
 						expect( watchdog.editor.getData() ).to.equal( '<p>foo</p><p>bar</p>' );
 
 						watchdog.destroy().then( res );
@@ -570,6 +569,44 @@ describe( 'Watchdog', () => {
 				} );
 			} );
 		} );
+
+		it( 'editor should be restarted with the latest available data before the crash', () => {
+			const watchdog = new Watchdog();
+
+			watchdog.setCreator( ( el, config ) => FakeEditor.create( el, config ) );
+			watchdog.setDestructor( editor => editor.destroy() );
+
+			// sinon.stub( window, 'onerror' ).value( undefined ); and similar don't work.
+			const originalErrorHandler = window.onerror;
+			window.onerror = undefined;
+
+			return watchdog.create( document.createElement( 'div' ), {
+				initialData: '<p>foo</p>',
+				plugins: [ Paragraph ]
+			} ).then( () => {
+				const getDataStub = sinon.stub( watchdog.editor, 'getData' )
+					.throwsException( new Error( 'Some error' ) );
+
+				setTimeout( () => throwCKEditorError( 'foo', watchdog.editor ) );
+
+				const doc = watchdog.editor.model.document;
+
+				watchdog.editor.model.change( writer => {
+					writer.insertText( 'bar', writer.createPositionAt( doc.getRoot(), 1 ) );
+				} );
+
+				return new Promise( res => {
+					watchdog.on( 'restart', () => {
+						window.onerror = originalErrorHandler;
+
+						sinon.assert.calledOnce( getDataStub );
+						expect( watchdog.editor.getData() ).to.equal( '<p>foo</p>' );
+
+						watchdog.destroy().then( res );
+					} );
+				} );
+			} );
+		} );
 	} );
 
 	describe( 'crashes', () => {