formatMessage crashes if no `id` is passed in production environment
charlie632 opened this issue Β· comments
Hi! π
Firstly, thanks for your work on this project! π
Today I used patch-package to patch react-intl@5.24.6
for the project I'm working on.
We've had some issues in production where if we miss passing an id
to a FormattedMessage
or a formatMessage
, the whole application breaks down. We know this is an error on our side, but It'd be good to fail gracefully if something like this happens. We think the development environment is a good place to catch these errors; that's why we throw the error there but return an empty string in production.
It would be great to have a built-in option for this in the library, as we use it for all our applications.
Here is the diff that solved my problem:
diff --git a/node_modules/react-intl/lib/src/components/useIntl.js b/node_modules/react-intl/lib/src/components/useIntl.js
index 0edaee5..266a4e9 100755
--- a/node_modules/react-intl/lib/src/components/useIntl.js
+++ b/node_modules/react-intl/lib/src/components/useIntl.js
@@ -1,8 +1,27 @@
import * as React from 'react';
import { Context } from './injectIntl';
import { invariantIntlContext } from '../utils';
+
+
+function safeFormatMessage(fmt) {
+ return (...args) => {
+ try {
+ return fmt(...args);
+ } catch (e) {
+ console.error('[@formatjs/react-intl] Error formatting message: ', e);
+ if (process.env.NODE_ENV !== 'production') {
+ throw e;
+ }
+ // Return empty string if there's an error. This allows the app to render.
+ return '';
+ }
+ };
+ }
+
+
+
export default function useIntl() {
var intl = React.useContext(Context);
invariantIntlContext(intl);
- return intl;
+ return { ...intl, formatMessage: safeFormatMessage(intl.formatMessage) };
}
I'd be happy to help with a PR if this solution is useful.
There is also a related issue on this but it is closed: #1108
This issue body was partially generated by patch-package.
are you using https://formatjs.io/docs/tooling/linter#no-id?
This has come up many times but unfortunately we won't relax this. This creates more footguns so using our linter is the solution to this problem.