常见引发异常场景及处理方式
- 访问不存在的属性
- 场景:当使用反射 API(如
Reflect.get()
)尝试访问对象上不存在的属性时,可能会引发错误。例如:
const obj = {};
Reflect.get(obj, 'nonexistentProperty');
- **处理方式**:可以在使用 `Reflect.get()` 时先通过 `Object.hasOwnProperty()` 检查属性是否存在,或者使用 `try - catch` 块捕获异常。
const obj = {};
if (obj.hasOwnProperty('nonexistentProperty')) {
Reflect.get(obj, 'nonexistentProperty');
} else {
console.log('属性不存在');
}
// 或者
try {
Reflect.get(obj, 'nonexistentProperty');
} catch (error) {
console.error('访问属性出错:', error);
}
- 操作不可配置的属性
- 场景:如果使用反射 API 尝试修改对象上不可配置(
configurable: false
)的属性,会引发异常。例如:
const obj = Object.defineProperty({}, 'prop', {
value: 10,
configurable: false
});
try {
Reflect.defineProperty(obj, 'prop', { value: 20 });
} catch (error) {
console.error('修改不可配置属性出错:', error);
}
- **处理方式**:在操作属性前先获取属性描述符(`Object.getOwnPropertyDescriptor()`),检查 `configurable` 是否为 `true`。如果不确定属性的配置情况,使用 `try - catch` 捕获异常。
const obj = Object.defineProperty({}, 'prop', {
value: 10,
configurable: false
});
const desc = Object.getOwnPropertyDescriptor(obj, 'prop');
if (desc && desc.configurable) {
Reflect.defineProperty(obj, 'prop', { value: 20 });
} else {
console.log('属性不可配置,无法修改');
}
- 对非对象目标操作
- 场景:反射 API 的许多方法(如
Reflect.get()
、Reflect.set()
等)要求第一个参数是对象。如果传入非对象值,会引发 TypeError
。例如:
Reflect.get(123, 'prop');
- **处理方式**:在使用反射 API 方法前,通过 `typeof` 检查第一个参数是否为对象。
const target = 123;
if (typeof target === 'object' && target!== null) {
Reflect.get(target, 'prop');
} else {
console.log('目标不是对象,无法操作');
}