mirror of
https://github.com/facebook/react-native.git
synced 2025-11-01 09:14:26 +00:00
d544fa20b7
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: <img width="802" alt="Screen Shot 2019-07-18 at 8 39 52 PM" src="https://user-images.githubusercontent.com/2192930/61501171-39218080-a99c-11e9-8e87-48ea413b3d01.png"> Lint: <img width="406" alt="Screen Shot 2019-07-18 at 8 43 35 PM" src="https://user-images.githubusercontent.com/2192930/61501318-dc729580-a99c-11e9-9264-c0232515352c.png"> Differential Revision: D16437956 Pulled By: cpojer fbshipit-source-id: ca3ce9c98ad585beb29c2bfeb81bbd14b2b1c700
51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
/**
|
|
* Copyright (c) Facebook, Inc. and its affiliates.
|
|
*
|
|
* This source code is licensed under the MIT license found in the
|
|
* LICENSE file in the root directory of this source tree.
|
|
*
|
|
* @format
|
|
* @flow
|
|
*/
|
|
|
|
'use strict';
|
|
|
|
/**
|
|
* Tries to stringify with JSON.stringify and toString, but catches exceptions
|
|
* (e.g. from circular objects) and always returns a string and never throws.
|
|
*/
|
|
function stringifySafe(arg: any): string {
|
|
let ret;
|
|
const type = typeof arg;
|
|
if (arg === undefined) {
|
|
ret = 'undefined';
|
|
} else if (arg === null) {
|
|
ret = 'null';
|
|
} else if (type === 'string') {
|
|
ret = '"' + arg + '"';
|
|
} else if (type === 'function') {
|
|
try {
|
|
ret = arg.toString();
|
|
} 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.
|
|
try {
|
|
ret = JSON.stringify(arg);
|
|
} catch (e) {
|
|
if (typeof arg.toString === 'function') {
|
|
try {
|
|
ret = arg.toString();
|
|
} catch (E) {}
|
|
}
|
|
}
|
|
}
|
|
return ret || '["' + type + '" failed to stringify]';
|
|
}
|
|
|
|
module.exports = stringifySafe;
|