JavaScript:如何在Promise函数中针对非法输入返回TypeError?
How to Reject a TypeError for Invalid Inputs in
objectToArray Great question! Your current objectToArray function handles valid Object of Object inputs correctly, but it lacks input validation to catch cases where the input doesn’t match the expected structure. Let’s fix that by adding checks to reject a proper TypeError when the input is invalid.
Modified Code with Input Validation
Here’s the updated function with robust validation logic:
function objectToArray(objectOfObject) { return new Promise((resolve, reject) => { // Check if input is a valid object (exclude null, since typeof null is "object") if (typeof objectOfObject !== 'object' || objectOfObject === null) { return reject(new TypeError('Input must be an Object of Objects, but received a non-object value')); } // Check if all values in the input are valid objects (exclude null) const hasInvalidValue = Object.values(objectOfObject).some(value => typeof value !== 'object' || value === null ); if (hasInvalidValue) { return reject(new TypeError('Input must be an Object of Objects, but some values are non-object')); } // Transform the object to array (without modifying the original objects) const newArray = Object.keys(objectOfObject).map(key => { // Use spread operator to create a copy of the original object const item = { ...objectOfObject[key] }; item.id = key; return item; }); resolve(newArray); }); }
Key Changes Explained
- Input Type Check: We first verify the input is an object and not
null(a quirk of JavaScript is thattypeof nullreturns"object"). If not, we reject with aTypeErrordescribing the issue. - Value Validation: We use
Object.values()andArray.some()to quickly check if any value in the input is not a valid object (again excludingnull). If any invalid value exists, we reject with another specificTypeError. - Avoid Mutating Original Objects: Instead of directly adding an
idproperty to the original objects, we create a copy using the spread operator ({ ...objectOfObject[key] }). This prevents unintended side effects on the original data. - Proper Error Instances: We reject with
TypeErrorinstances (not just strings) so callers can easily identify the error type usinginstanceof TypeError.
Usage Examples
Test the function with valid and invalid inputs to see the validation in action:
// Valid input: Object of Objects objectToArray({ user1: { name: 'Alice', age: 30 }, user2: { name: 'Bob', age: 25 } }) .then(result => console.log(result)) .catch(err => console.error(err)); // Invalid input: Non-object value objectToArray('this is a string') .catch(err => console.error(err)); // Logs TypeError: Input must be an Object of Objects... // Invalid input: Contains a non-object value objectToArray({ user1: { name: 'Alice' }, user2: 'Bob' // This is a string, not an object }) .catch(err => console.error(err)); // Logs TypeError: Input must be an Object of Objects...
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

