Skip to content

Commit 836784f

Browse files
authored
Merge pull request reduxjs#4055 from reduxjs/feature/update-error-messages
2 parents 756ba19 + f843f6e commit 836784f

10 files changed

+190
-61
lines changed

.codesandbox/ci.json

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"sandboxes": [
3+
"vanilla",
4+
"vanilla-ts"
5+
],
6+
"node": "14"
7+
}

errors.json

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
11
{
2-
"0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function.",
3-
"1": "Expected the enhancer to be a function.",
4-
"2": "Expected the reducer to be a function.",
2+
"0": "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.",
3+
"1": "Expected the enhancer to be a function. Instead, received: ''",
4+
"2": "Expected the root reducer to be a function. Instead, received: ''",
55
"3": "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.",
6-
"4": "Expected the listener to be a function.",
6+
"4": "Expected the listener to be a function. Instead, received: ''",
77
"5": "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.",
88
"6": "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.",
9-
"7": "Actions must be plain objects. Use custom middleware for async actions.",
10-
"8": "Actions may not have an undefined \"type\" property. Have you misspelled a constant?",
9+
"7": "Actions must be plain objects. Instead, the actual type was: ''. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.",
10+
"8": "Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.",
1111
"9": "Reducers may not dispatch actions.",
12-
"10": "Expected the nextReducer to be a function.",
13-
"11": "Expected the observer to be an object.",
14-
"12": "bindActionCreators expected an object or a function, instead received . Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?",
15-
"13": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.",
16-
"14": "Reducer \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.",
17-
"15": "Reducer \"\" returned undefined when probed with a random type. Don't try to handle or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.",
18-
"16": "Super expression must either be null or a function"
12+
"10": "Expected the nextReducer to be a function. Instead, received: '",
13+
"11": "Expected the observer to be an object. Instead, received: ''",
14+
"12": "The slice reducer for key \"\" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.",
15+
"13": "The slice reducer for key \"\" returned undefined when probed with a random type. Don't try to handle '' or other actions in \"redux/*\" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.",
16+
"14": "When called with an action of type , the slice reducer for key \"\" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.",
17+
"15": "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.",
18+
"16": "bindActionCreators expected an object or a function, but instead received: ''. Did you write \"import ActionCreators from\" instead of \"import * as ActionCreators from\"?"
1919
}

scripts/mangleErrors.js

+5
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,11 @@ module.exports = babel => {
8989

9090
const errorMsgLiteral = evalToString(path.node.argument.arguments[0])
9191

92+
if (errorMsgLiteral.includes('Super expression')) {
93+
// ignore Babel runtime error message
94+
return
95+
}
96+
9297
// Attempt to get the existing index of the error. If it is not found, add it to the array as a new error.
9398
let errorIndex = errors.indexOf(errorMsgLiteral)
9499
if (errorIndex === -1) {

src/bindActionCreators.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
ActionCreator,
55
ActionCreatorsMapObject
66
} from './types/actions'
7+
import { kindOf } from './utils/kindOf'
78

89
function bindActionCreator<A extends AnyAction = AnyAction>(
910
actionCreator: ActionCreator<A>,
@@ -64,9 +65,9 @@ export default function bindActionCreators(
6465

6566
if (typeof actionCreators !== 'object' || actionCreators === null) {
6667
throw new Error(
67-
`bindActionCreators expected an object or a function, instead received ${
68-
actionCreators === null ? 'null' : typeof actionCreators
69-
}. ` +
68+
`bindActionCreators expected an object or a function, but instead received: '${kindOf(
69+
actionCreators
70+
)}'. ` +
7071
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
7172
)
7273
}

src/combineReducers.ts

+15-24
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,7 @@ import { CombinedState } from './types/store'
1010
import ActionTypes from './utils/actionTypes'
1111
import isPlainObject from './utils/isPlainObject'
1212
import warning from './utils/warning'
13-
14-
function getUndefinedStateErrorMessage(key: string, action: Action) {
15-
const actionType = action && action.type
16-
const actionDescription =
17-
(actionType && `action "${String(actionType)}"`) || 'an action'
18-
19-
return (
20-
`Given ${actionDescription}, reducer "${key}" returned undefined. ` +
21-
`To ignore an action, you must explicitly return the previous state. ` +
22-
`If you want this reducer to hold no value, you can return null instead of undefined.`
23-
)
24-
}
13+
import { kindOf } from './utils/kindOf'
2514

2615
function getUnexpectedStateShapeWarningMessage(
2716
inputState: object,
@@ -43,14 +32,10 @@ function getUnexpectedStateShapeWarningMessage(
4332
}
4433

4534
if (!isPlainObject(inputState)) {
46-
const match = Object.prototype.toString
47-
.call(inputState)
48-
.match(/\s([a-z|A-Z]+)/)
49-
const matchType = match ? match[1] : ''
5035
return (
51-
`The ${argumentName} has unexpected type of "` +
52-
matchType +
53-
`". Expected argument to be an object with the following ` +
36+
`The ${argumentName} has unexpected type of "${kindOf(
37+
inputState
38+
)}". Expected argument to be an object with the following ` +
5439
`keys: "${reducerKeys.join('", "')}"`
5540
)
5641
}
@@ -82,7 +67,7 @@ function assertReducerShape(reducers: ReducersMapObject) {
8267

8368
if (typeof initialState === 'undefined') {
8469
throw new Error(
85-
`Reducer "${key}" returned undefined during initialization. ` +
70+
`The slice reducer for key "${key}" returned undefined during initialization. ` +
8671
`If the state passed to the reducer is undefined, you must ` +
8772
`explicitly return the initial state. The initial state may ` +
8873
`not be undefined. If you don't want to set a value for this reducer, ` +
@@ -96,8 +81,8 @@ function assertReducerShape(reducers: ReducersMapObject) {
9681
}) === 'undefined'
9782
) {
9883
throw new Error(
99-
`Reducer "${key}" returned undefined when probed with a random type. ` +
100-
`Don't try to handle ${ActionTypes.INIT} or other actions in "redux/*" ` +
84+
`The slice reducer for key "${key}" returned undefined when probed with a random type. ` +
85+
`Don't try to handle '${ActionTypes.INIT}' or other actions in "redux/*" ` +
10186
`namespace. They are considered private. Instead, you must return the ` +
10287
`current state for any unknown actions, unless it is undefined, ` +
10388
`in which case you must return the initial state, regardless of the ` +
@@ -197,8 +182,14 @@ export default function combineReducers(reducers: ReducersMapObject) {
197182
const previousStateForKey = state[key]
198183
const nextStateForKey = reducer(previousStateForKey, action)
199184
if (typeof nextStateForKey === 'undefined') {
200-
const errorMessage = getUndefinedStateErrorMessage(key, action)
201-
throw new Error(errorMessage)
185+
const actionType = action && action.type
186+
throw new Error(
187+
`When called with an action of type ${
188+
actionType ? `"${String(actionType)}"` : '(unknown type)'
189+
}, the slice reducer for key "${key}" returned undefined. ` +
190+
`To ignore an action, you must explicitly return the previous state. ` +
191+
`If you want this reducer to hold no value, you can return null instead of undefined.`
192+
)
202193
}
203194
nextState[key] = nextStateForKey
204195
hasChanged = hasChanged || nextStateForKey !== previousStateForKey

src/createStore.ts

+31-10
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Action } from './types/actions'
1212
import { Reducer } from './types/reducers'
1313
import ActionTypes from './utils/actionTypes'
1414
import isPlainObject from './utils/isPlainObject'
15+
import { kindOf } from './utils/kindOf'
1516

1617
/**
1718
* Creates a Redux store that holds the state tree.
@@ -74,7 +75,7 @@ export default function createStore<
7475
throw new Error(
7576
'It looks like you are passing several store enhancers to ' +
7677
'createStore(). This is not supported. Instead, compose them ' +
77-
'together to a single function.'
78+
'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.'
7879
)
7980
}
8081

@@ -85,7 +86,11 @@ export default function createStore<
8586

8687
if (typeof enhancer !== 'undefined') {
8788
if (typeof enhancer !== 'function') {
88-
throw new Error('Expected the enhancer to be a function.')
89+
throw new Error(
90+
`Expected the enhancer to be a function. Instead, received: '${kindOf(
91+
enhancer
92+
)}'`
93+
)
8994
}
9095

9196
return enhancer(createStore)(
@@ -95,7 +100,11 @@ export default function createStore<
95100
}
96101

97102
if (typeof reducer !== 'function') {
98-
throw new Error('Expected the reducer to be a function.')
103+
throw new Error(
104+
`Expected the root reducer to be a function. Instead, received: '${kindOf(
105+
reducer
106+
)}'`
107+
)
99108
}
100109

101110
let currentReducer = reducer
@@ -159,7 +168,11 @@ export default function createStore<
159168
*/
160169
function subscribe(listener: () => void) {
161170
if (typeof listener !== 'function') {
162-
throw new Error('Expected the listener to be a function.')
171+
throw new Error(
172+
`Expected the listener to be a function. Instead, received: '${kindOf(
173+
listener
174+
)}'`
175+
)
163176
}
164177

165178
if (isDispatching) {
@@ -225,15 +238,15 @@ export default function createStore<
225238
function dispatch(action: A) {
226239
if (!isPlainObject(action)) {
227240
throw new Error(
228-
'Actions must be plain objects. ' +
229-
'Use custom middleware for async actions.'
241+
`Actions must be plain objects. Instead, the actual type was: '${kindOf(
242+
action
243+
)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`
230244
)
231245
}
232246

233247
if (typeof action.type === 'undefined') {
234248
throw new Error(
235-
'Actions may not have an undefined "type" property. ' +
236-
'Have you misspelled a constant?'
249+
'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'
237250
)
238251
}
239252

@@ -271,7 +284,11 @@ export default function createStore<
271284
nextReducer: Reducer<NewState, NewActions>
272285
): Store<ExtendState<NewState, StateExt>, NewActions, StateExt, Ext> & Ext {
273286
if (typeof nextReducer !== 'function') {
274-
throw new Error('Expected the nextReducer to be a function.')
287+
throw new Error(
288+
`Expected the nextReducer to be a function. Instead, received: '${kindOf(
289+
nextReducer
290+
)}`
291+
)
275292
}
276293

277294
// TODO: do this more elegantly
@@ -314,7 +331,11 @@ export default function createStore<
314331
*/
315332
subscribe(observer: unknown) {
316333
if (typeof observer !== 'object' || observer === null) {
317-
throw new TypeError('Expected the observer to be an object.')
334+
throw new TypeError(
335+
`Expected the observer to be an object. Instead, received: '${kindOf(
336+
observer
337+
)}'`
338+
)
318339
}
319340

320341
function observeState() {

src/utils/kindOf.ts

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
export function kindOf(val: any): string {
2+
let typeOfVal: string = typeof val
3+
4+
if (process.env.NODE_ENV !== 'production') {
5+
// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of
6+
function miniKindOf(val: any) {
7+
if (val === void 0) return 'undefined'
8+
if (val === null) return 'null'
9+
10+
const type = typeof val
11+
switch (type) {
12+
case 'boolean':
13+
case 'string':
14+
case 'number':
15+
case 'symbol':
16+
case 'function': {
17+
return type
18+
}
19+
}
20+
21+
if (Array.isArray(val)) return 'array'
22+
if (isDate(val)) return 'date'
23+
if (isError(val)) return 'error'
24+
25+
const constructorName = ctorName(val)
26+
switch (constructorName) {
27+
case 'Symbol':
28+
case 'Promise':
29+
case 'WeakMap':
30+
case 'WeakSet':
31+
case 'Map':
32+
case 'Set':
33+
return constructorName
34+
}
35+
36+
// other
37+
return type.slice(8, -1).toLowerCase().replace(/\s/g, '')
38+
}
39+
40+
function ctorName(val: any): string | null {
41+
return typeof val.constructor === 'function' ? val.constructor.name : null
42+
}
43+
44+
function isError(val: any) {
45+
return (
46+
val instanceof Error ||
47+
(typeof val.message === 'string' &&
48+
val.constructor &&
49+
typeof val.constructor.stackTraceLimit === 'number')
50+
)
51+
}
52+
53+
function isDate(val: any) {
54+
if (val instanceof Date) return true
55+
return (
56+
typeof val.toDateString === 'function' &&
57+
typeof val.getDate === 'function' &&
58+
typeof val.setDate === 'function'
59+
)
60+
}
61+
62+
typeOfVal = miniKindOf(val)
63+
}
64+
65+
return typeOfVal
66+
}

test/bindActionCreators.spec.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -77,17 +77,17 @@ describe('bindActionCreators', () => {
7777
expect(() => {
7878
bindActionCreators(undefined, store.dispatch)
7979
}).toThrow(
80-
'bindActionCreators expected an object or a function, instead received undefined. ' +
81-
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
80+
`bindActionCreators expected an object or a function, but instead received: 'undefined'. ` +
81+
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
8282
)
8383
})
8484

8585
it('throws for a null actionCreator', () => {
8686
expect(() => {
8787
bindActionCreators(null, store.dispatch)
8888
}).toThrow(
89-
'bindActionCreators expected an object or a function, instead received null. ' +
90-
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
89+
`bindActionCreators expected an object or a function, but instead received: 'null'. ` +
90+
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
9191
)
9292
})
9393

@@ -98,8 +98,8 @@ describe('bindActionCreators', () => {
9898
store.dispatch
9999
)
100100
}).toThrow(
101-
'bindActionCreators expected an object or a function, instead received string. ' +
102-
'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'
101+
`bindActionCreators expected an object or a function, but instead received: 'string'. ` +
102+
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
103103
)
104104
})
105105
})

test/combineReducers.spec.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ describe('Utils', () => {
264264

265265
createStore(reducer, (1 as unknown) as ShapeState)
266266
expect(spy.mock.calls[2][0]).toMatch(
267-
/createStore has unexpected type of "Number".*keys: "foo", "baz"/
267+
/createStore has unexpected type of "number".*keys: "foo", "baz"/
268268
)
269269

270270
reducer(({ corge: 2 } as unknown) as ShapeState, nullAction)
@@ -279,7 +279,7 @@ describe('Utils', () => {
279279

280280
reducer((1 as unknown) as ShapeState, nullAction)
281281
expect(spy.mock.calls[5][0]).toMatch(
282-
/reducer has unexpected type of "Number".*keys: "foo", "baz"/
282+
/reducer has unexpected type of "number".*keys: "foo", "baz"/
283283
)
284284

285285
spy.mockClear()

0 commit comments

Comments
 (0)