Skip to content

Commit

Permalink
Compile invariant directly to throw expressions (#15071)
Browse files Browse the repository at this point in the history
* Transform invariant to custom error type

This transforms calls to the invariant module:

```js
invariant(condition, 'A %s message that contains %s', adj, noun);
```

Into throw statements:

```js
if (!condition) {
  if (__DEV__) {
    throw ReactError(`A ${adj} message that contains ${noun}`);
  } else {
    throw ReactErrorProd(ERR_CODE, adj, noun);
  }
}
```

The only thing ReactError does is return an error whose name is set
to "Invariant Violation" to match the existing behavior.

ReactErrorProd is a special version used in production that throws
a minified error code, with a link to see to expanded form. This
replaces the reactProdInvariant module.

As a next step, I would like to replace our use of the invariant module
for user facing errors by transforming normal Error constructors to
ReactError and ReactErrorProd. (We can continue using invariant for
internal React errors that are meant to be unreachable, which was the
original purpose of invariant.)

* Use numbers instead of strings for error codes

* Use arguments instead of an array

I wasn't sure about this part so I asked Sebastian, and his rationale
was that using arguments will make ReactErrorProd slightly slower, but
using an array will likely make all the functions that throw slightly
slower to compile, so it's hard to say which way is better. But since
ReactErrorProd is in an error path, and fewer bytes is generally better,
no array is good.

* Casing nit
  • Loading branch information
acdlite authored Mar 18, 2019
1 parent df7b87d commit 42c3c96
Show file tree
Hide file tree
Showing 17 changed files with 462 additions and 360 deletions.
19 changes: 19 additions & 0 deletions packages/shared/ReactError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* 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.
*
*/

// Do not require this module directly! Use a normal error constructor with
// template literal strings. The messages will be converted to ReactError during
// build, and in production they will be minified.

function ReactError(message) {
const error = new Error(message);
error.name = 'Invariant Violation';
return error;
}

export default ReactError;
25 changes: 25 additions & 0 deletions packages/shared/ReactErrorProd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* 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.
*
*/

// Do not require this module directly! Use a normal error constructor with
// template literal strings. The messages will be converted to ReactError during
// build, and in production they will be minified.

function ReactErrorProd(code) {
let url = 'https://reactjs.org/docs/error-decoder.html?invariant=' + code;
for (let i = 1; i < arguments.length; i++) {
url += '&args[]=' + encodeURIComponent(arguments[i]);
}
return new Error(
`Minified React error #${code}; visit ${url} for the full message or ` +
'use the non-minified dev environment for full errors and additional ' +
'helpful warnings. ',
);
}

export default ReactErrorProd;
72 changes: 72 additions & 0 deletions packages/shared/__tests__/ReactError-test.internal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* 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.
*
* @emails react-core
*/
'use strict';

let React;
let ReactDOM;

describe('ReactError', () => {
let globalErrorMock;

beforeEach(() => {
if (!__DEV__) {
// In production, our Jest environment overrides the global Error
// class in order to decode error messages automatically. However
// this is a single test where we actually *don't* want to decode
// them. So we assert that the OriginalError exists, and temporarily
// set the global Error object back to it.
globalErrorMock = global.Error;
global.Error = globalErrorMock.OriginalError;
expect(typeof global.Error).toBe('function');
}
jest.resetModules();
React = require('react');
ReactDOM = require('react-dom');
});

afterEach(() => {
if (!__DEV__) {
global.Error = globalErrorMock;
}
});

if (__DEV__) {
it('should throw errors whose name is "Invariant Violation"', () => {
let error;
try {
React.useState();
} catch (e) {
error = e;
}
expect(error.name).toEqual('Invariant Violation');
});
} else {
it('should error with minified error code', () => {
expect(() => ReactDOM.render('Hi', null)).toThrowError(
'Minified React error #200; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=200' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
});
it('should serialize arguments', () => {
function Oops() {
return;
}
Oops.displayName = '#wtf';
const container = document.createElement('div');
expect(() => ReactDOM.render(<Oops />, container)).toThrowError(
'Minified React error #152; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=152&args[]=%23wtf' +
' for the full message or use the non-minified dev environment' +
' for full errors and additional helpful warnings.',
);
});
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
*/
'use strict';

let reactProdInvariant;
let ReactErrorProd;

describe('reactProdInvariant', () => {
describe('ReactErrorProd', () => {
let globalErrorMock;

beforeEach(() => {
Expand All @@ -25,7 +25,7 @@ describe('reactProdInvariant', () => {
expect(typeof global.Error).toBe('function');
}
jest.resetModules();
reactProdInvariant = require('shared/reactProdInvariant').default;
ReactErrorProd = require('shared/ReactErrorProd').default;
});

afterEach(() => {
Expand All @@ -36,7 +36,7 @@ describe('reactProdInvariant', () => {

it('should throw with the correct number of `%s`s in the URL', () => {
expect(function() {
reactProdInvariant(124, 'foo', 'bar');
throw ReactErrorProd(124, 'foo', 'bar');
}).toThrowError(
'Minified React error #124; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=124&args[]=foo&args[]=bar' +
Expand All @@ -45,7 +45,7 @@ describe('reactProdInvariant', () => {
);

expect(function() {
reactProdInvariant(20);
throw ReactErrorProd(20);
}).toThrowError(
'Minified React error #20; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=20' +
Expand All @@ -54,7 +54,7 @@ describe('reactProdInvariant', () => {
);

expect(function() {
reactProdInvariant(77, '<div>', '&?bar');
throw ReactErrorProd(77, '<div>', '&?bar');
}).toThrowError(
'Minified React error #77; visit ' +
'https://reactjs.org/docs/error-decoder.html?invariant=77&args[]=%3Cdiv%3E&args[]=%26%3Fbar' +
Expand Down
8 changes: 0 additions & 8 deletions packages/shared/forks/invariant.www.js

This file was deleted.

37 changes: 4 additions & 33 deletions packages/shared/invariant.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,38 +17,9 @@
* will remain to ensure logic does not differ in production.
*/

let validateFormat = () => {};

if (__DEV__) {
validateFormat = function(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}

export default function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);

if (!condition) {
let error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.',
);
} else {
const args = [a, b, c, d, e, f];
let argIndex = 0;
error = new Error(
format.replace(/%s/g, function() {
return args[argIndex++];
}),
);
error.name = 'Invariant Violation';
}

error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
throw new Error(
'Internal React error: invariant() is meant to be replaced at compile ' +
'time. There is no runtime version.',
);
}
43 changes: 0 additions & 43 deletions packages/shared/reactProdInvariant.js

This file was deleted.

29 changes: 16 additions & 13 deletions scripts/error-codes/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
The error code system substitutes React's invariant error messages with error IDs to provide a better debugging support in production. Check out the blog post [here](https://reactjs.org/blog/2016/07/11/introducing-reacts-error-code-system.html).
The error code system substitutes React's error messages with error IDs to
provide a better debugging support in production. Check out the blog post
[here](https://reactjs.org/blog/2016/07/11/introducing-reacts-error-code-system.html).

## Note for cutting a new React release
1. For each release, we run `yarn build -- --extract-errors` to update the error codes before calling `yarn build`. The build step uses `codes.json` for a production (minified) build; there should be no warning like `Error message "foo" cannot be found` for a successful release.
2. The updated `codes.json` file should be synced back to the master branch. The error decoder page in our documentation site uses `codes.json` from master; if the json file has been updated, the docs site should also be rebuilt (`rake copy_error_codes` is included in the default `rake release` task).
3. Be certain to run `yarn build -- --extract-errors` directly in the release branch (if not master) to ensure the correct error codes are generated. These error messages might be changed/removed before cutting a new release, and we don't want to add intermediate/temporary error messages to `codes.json`. However, if a PR changes an existing error message and there's a specific production test (which is rare), it's ok to update `codes.json` for that. Please use `yarn build -- --extract-errors` and don't edit the file manually.

## Structure
The error code system consists of 5 parts:
- [`codes.json`](https://github.com/facebook/react/blob/master/scripts/error-codes/codes.json) contains the mapping from IDs to error messages. This file is generated by the Gulp plugin and is used by both the Babel plugin and the error decoder page in our documentation. This file is append-only, which means an existing code in the file will never be changed/removed.
- [`extract-errors.js`](https://github.com/facebook/react/blob/master/scripts/error-codes/extract-errors.js) is an node script that traverses our codebase and updates `codes.json`. Use it by calling `yarn build -- --extract-errors`.
- [`replace-invariant-error-codes.js`](https://github.com/facebook/react/blob/master/scripts/error-codes/replace-invariant-error-codes.js) is a Babel pass that rewrites error messages to IDs for a production (minified) build.
- [`reactProdInvariant.js`](https://github.com/facebook/react/blob/master/src/shared/utils/reactProdInvariant.js) is the replacement for `invariant` in production. This file gets imported by the Babel plugin and should _not_ be used manually.
- [`ErrorDecoderComponent`](https://github.com/facebook/react/blob/master/docs/_js/ErrorDecoderComponent.js) is a React component that lives at https://reactjs.org/docs/error-decoder.html. This page takes parameters like `?invariant=109&args[]=Foo` and displays a corresponding error message. Our documentation site's [`Rakefile`](https://github.com/facebook/react/blob/master/docs/Rakefile#L64-L69) has a task (`bundle exec rake copy_error_codes`) for adding the latest `codes.json` to the error decoder page. This task is included in the default `bundle exec rake release` task.
- [`codes.json`](https://github.com/facebook/react/blob/master/scripts/error-codes/codes.json)
contains the mapping from IDs to error messages. This file is generated by the
Gulp plugin and is used by both the Babel plugin and the error decoder page in
our documentation. This file is append-only, which means an existing code in
the file will never be changed/removed.
- [`extract-errors.js`](https://github.com/facebook/react/blob/master/scripts/error-codes/extract-errors.js)
is an node script that traverses our codebase and updates `codes.json`. You
can test it by running `yarn build -- --extract-errors`, but you should only
commit changes to this file when running a release. (The release tool will
perform this step automatically.)
- [`minify-error-codes`](https://github.com/facebook/react/blob/master/scripts/error-codes/minify-error-codes)
is a Babel pass that rewrites error messages to IDs for a production
(minified) build.
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`error transform should correctly transform invariants that are not in the error codes map 1`] = `
"import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
throw _ReactError(\`This is not a real error message.\`);
}
})();"
`;

exports[`error transform should handle escaped characters 1`] = `
"import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
throw _ReactError(\`What's up?\`);
}
})();"
`;

exports[`error transform should only add \`ReactError\` and \`ReactErrorProd\` once each 1`] = `
"import _ReactErrorProd from 'shared/ReactErrorProd';
import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
if (__DEV__) {
throw _ReactError(\`Do not override existing functions.\`);
} else {
throw _ReactErrorProd(16);
}
}
})();
(function () {
if (!condition) {
if (__DEV__) {
throw _ReactError(\`Do not override existing functions.\`);
} else {
throw _ReactErrorProd(16);
}
}
})();"
`;
exports[`error transform should replace simple invariant calls 1`] = `
"import _ReactErrorProd from 'shared/ReactErrorProd';
import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
if (__DEV__) {
throw _ReactError(\`Do not override existing functions.\`);
} else {
throw _ReactErrorProd(16);
}
}
})();"
`;
exports[`error transform should support invariant calls with a concatenated template string and args 1`] = `
"import _ReactErrorProd from 'shared/ReactErrorProd';
import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
if (__DEV__) {
throw _ReactError(\`Expected a component class, got \${Foo}.\${Bar}\`);
} else {
throw _ReactErrorProd(18, Foo, Bar);
}
}
})();"
`;
exports[`error transform should support invariant calls with args 1`] = `
"import _ReactErrorProd from 'shared/ReactErrorProd';
import _ReactError from 'shared/ReactError';
import invariant from 'shared/invariant';
(function () {
if (!condition) {
if (__DEV__) {
throw _ReactError(\`Expected \${foo} target to be an array; got \${bar}\`);
} else {
throw _ReactErrorProd(7, foo, bar);
}
}
})();"
`;
Loading

0 comments on commit 42c3c96

Please sign in to comment.