From d544fa20b7748dbd8d979ed13512e6674fa39a97 Mon Sep 17 00:00:00 2001 From: Dan Reynolds Date: Tue, 23 Jul 2019 02:39:56 -0700 Subject: [PATCH] add support for stringifying error object messages to stringifySafe (#25723) Summary: Error objects logged as part of the arguments to `console.error` such as from [rejected es6 promises](https://github.com/zloirock/core-js/blob/v2/modules/es6.promise.js#L110) contain the error that the user would want to see as the error object's message, but is not captured by `stringifySafe`. Here we modify it to if the logged value is an error object print the error similar to chrome: ``` const error = new Error('error'); stringifySafe(error); // Error: error ``` Versus the current behavior which does not recognize the error type and instead tries to stringify the it as an object: ``` JSON.stringify(new Error('error')) // "{}" ``` ## Changelog [JavaScript] [Changed] - Add support for stringifying error object messages to safeStringify Pull Request resolved: https://github.com/facebook/react-native/pull/25723 Test Plan: Tests: Screen Shot 2019-07-18 at 8 39 52 PM Lint: Screen Shot 2019-07-18 at 8 43 35 PM Differential Revision: D16437956 Pulled By: cpojer fbshipit-source-id: ca3ce9c98ad585beb29c2bfeb81bbd14b2b1c700 --- Libraries/Utilities/__tests__/stringifySafe-test.js | 6 ++++++ Libraries/Utilities/stringifySafe.js | 2 ++ 2 files changed, 8 insertions(+) diff --git a/Libraries/Utilities/__tests__/stringifySafe-test.js b/Libraries/Utilities/__tests__/stringifySafe-test.js index b7eb1f21192..c259caf20a7 100644 --- a/Libraries/Utilities/__tests__/stringifySafe-test.js +++ b/Libraries/Utilities/__tests__/stringifySafe-test.js @@ -47,4 +47,10 @@ describe('stringifySafe', () => { const result = stringifySafe(arg); expect(result).toEqual('["object" failed to stringify]'); }); + + it('stringifySafe stringifies error messages', () => { + const error = new Error('error'); + const result = stringifySafe(error); + expect(result).toEqual('Error: error'); + }); }); diff --git a/Libraries/Utilities/stringifySafe.js b/Libraries/Utilities/stringifySafe.js index 73e81a345db..d562a911e97 100644 --- a/Libraries/Utilities/stringifySafe.js +++ b/Libraries/Utilities/stringifySafe.js @@ -29,6 +29,8 @@ function stringifySafe(arg: any): string { } catch (e) { ret = '[function unknown]'; } + } else if (arg instanceof Error) { + ret = arg.name + ': ' + arg.message; } else { // Perform a try catch, just in case the object has a circular // reference or stringify throws for some other reason.