From 2d21364587f0a97dd6c23efb91fa1d285e1f2db7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 10 Jul 2020 15:03:11 +0800 Subject: [PATCH] Throw the error instead of return null in instantiate and addComponent (#6940) * Throw the error instead of return null in instantiate and addComponent * Update --- cocos/core/data/instantiate.ts | 114 ++++++++-------- cocos/core/data/object.ts | 167 ++++++++++++++---------- cocos/core/scene-graph/base-node-dev.ts | 9 +- cocos/core/scene-graph/base-node.ts | 40 +++--- cocos/core/scene-graph/scene.ts | 8 +- 5 files changed, 178 insertions(+), 160 deletions(-) diff --git a/cocos/core/data/instantiate.ts b/cocos/core/data/instantiate.ts index 0b79483505..cf312f8bd0 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -32,71 +32,79 @@ import { isDomNode } from '../utils/misc'; import { ValueType } from '../value-types'; import { CCObject } from './object'; import { js } from '../utils'; -import { errorID, warn } from '../platform/debug'; +import { errorID, getError, warn } from '../platform/debug'; import { DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; import Prefab from '../assets/prefab'; import { Node } from '../scene-graph/node'; -// @ts-ignore const Destroyed = CCObject.Flags.Destroyed; -// @ts-ignore const PersistentMask = CCObject.Flags.PersistentMask; const objsToClearTmpVar: any = []; // used to reset _iN$t variable /** - * @en Clones the object `original` and returns the clone, or instantiate a node from the Prefab. - * @zh 克隆指定的任意类型的对象,或者从 Prefab 实例化出新节点。 - * (Instantiate 时,function 和 dom 等非可序列化对象会直接保留原有引用,Asset 会直接进行浅拷贝,可序列化类型会进行深拷贝。) - * @param original - An existing object that you want to make a copy of. - * @return {} the newly instantiated object + * Invoke _instantiate method if supplied. + * The _instantiate callback will be called only on the root object, its associated object will not be called. + * @param instantiated If supplied, _instantiate just need to initialize the instantiated object, no need to create new object by itself. + * @returns The instantiated object. + */ +type CustomInstantiation = (this: T, instantiated?: T) => T; + +/** + * @zh 从 Prefab 实例化出新节点。 + * @en Instantiate a node from the Prefab. + * @param prefab The prefab. + * @returns The instantiated node. * @example - * ```typescript - * // instantiate node from prefab - * var scene = cc.director.getScene(); - * var node = cc.instantiate(prefabAsset); - * node.parent = scene; - * // clone node - * var scene = cc.director.getScene(); - * var node = cc.instantiate(targetNode); - * node.parent = scene; + * ```ts + * import { instantiate, director } from 'cc'; + * // Instantiate node from prefab. + * const node = instantiate(prefabAsset); + * node.parent = director.getScene(); * ``` */ -function instantiate (original: Prefab|Node|Object, internal_force?: Node|Object): Node | null { - if (!internal_force) { - if (typeof original !== 'object' || Array.isArray(original)) { - if (DEV) { - errorID(6900); +function instantiate (prefab: Prefab): Node; + +/** + * @en Clones the object `original. + * @zh 克隆指定的任意类型的对象。 + * @param original An existing object that you want to make a copy of. + * It can be any JavaScript object(`typeof original === 'object'`) but: + * - it shall not be array or null; + * - it shall not be object of `Asset`; + * - if it's an object of `CCObject`, it should not have been destroyed. + * @returns The newly instantiated object. + * @example + * ```ts + * import { instantiate, director } from 'cc'; + * // Clone a node. + * const node = instantiate(targetNode); + * node.parent = director.getScene(); + * ``` + */ +function instantiate (original: T): T; + +function instantiate (original: any, internalForce?: boolean) { + if (!internalForce) { + if (DEV) { + if (typeof original !== 'object' || Array.isArray(original)) { + throw new TypeError(getError(6900)); } - return null; - } - if (!original) { - if (DEV) { - errorID(6901); + if (!original) { + throw new TypeError(getError(6901)); } - return null; - } - if (!legacyCC.isValid(original)) { - if (DEV) { - errorID(6902); + if (!legacyCC.isValid(original)) { + throw new TypeError(getError(6901)); + } + if (original instanceof legacyCC.Component) { + warn('Should not instantiate a single cc.Component directly, you must instantiate the entire node.'); } - return null; - } - if (DEV && original instanceof legacyCC.Component) { - warn('Should not instantiate a single cc.Component directly, you must instantiate the entire node.'); } } let clone; if (original instanceof CCObject) { - original = original as CCObject; - // Invoke _instantiate method if supplied. - // The _instantiate callback will be called only on the root object, its associated object will not be called. - // @callback associated - // @param {Object} [instantiated] - If supplied, _instantiate just need to initialize the instantiated object, - // no need to create new object by itself. - // @returns {Object} - the instantiated object // @ts-ignore if (original._instantiate) { legacyCC.game._isCloning = true; @@ -106,11 +114,7 @@ function instantiate (original: Prefab|Node|Object, internal_force?: Node|Object return clone; } else if (original instanceof legacyCC.Asset) { - // 不允许用通用方案实例化资源 - if (DEV) { - errorID(6903); - } - return null; + throw new TypeError(getError(6903)); } } @@ -133,17 +137,13 @@ function instantiate (original: Prefab|Node|Object, internal_force?: Node|Object * @private */ function doInstantiate (obj, parent?) { - if (Array.isArray(obj)) { - if (DEV) { - errorID(6904); + if (DEV) { + if (Array.isArray(obj)) { + throw new TypeError(getError(6904)); } - return null; - } - if (isDomNode && isDomNode(obj)) { - if (DEV) { - errorID(6905); + if (isDomNode && isDomNode(obj)) { + throw new TypeError(getError(6905)); } - return null; } let clone; diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index add4e777fb..1dca3aadf9 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -412,93 +412,22 @@ CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); * @private */ js.value(CCObject, 'Flags', { - Destroyed, - // ToDestroy: ToDestroy, - - /** - * @en The object will not be saved. - * @zh 该对象将不会被保存。 - */ DontSave, - - /** - * @en The object will not be saved when building a player. - * @zh 构建项目时,该对象将不会被保存。 - */ EditorOnly, - Dirty, - - /** - * @en Dont destroy automatically when loading a new scene. - * @zh 加载一个新场景时,不自动删除该对象 - * @property DontDestroy - * @private - */ DontDestroy, - PersistentMask, - - // FLAGS FOR ENGINE - Destroying, - - /** - * @en The node is deactivating. - * @zh 节点正在反激活的过程中。 - * @private - */ Deactivating, - - /** - * @en The lock node, when the node is locked, cannot be clicked in the scene. - * @zh 锁定节点,锁定后场景内不能点击 - * @private - */ LockedInEditor, - - /// ** - // * @en - // * Hide in game and hierarchy. - // * This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). - // * @zh - // * 在游戏和层级中隐藏该对象。
- // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // * @property {Number} HideInGame - // */ - // HideInGame: HideInGame, - - // FLAGS FOR EDITOR - - /// ** - // * @en This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). - // * @zh 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // */ HideInHierarchy, - - /// ** - // * @en - // * Hide in game view, hierarchy, and scene view... etc. - // * This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). - // * @zh - // * 在游戏视图,层级,场景视图等等...中隐藏该对象。 - // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // */ - // Hide: Hide, - - //// UUID Registered in editor - // RegisteredInEditor: RegisteredInEditor, - - // FLAGS FOR COMPONENT - IsPreloadStarted, IsOnLoadStarted, IsOnLoadCalled, IsOnEnableCalled, IsStartCalled, IsEditorOnEnableCalled, - IsPositionLocked, IsRotationLocked, IsScaleLocked, @@ -506,6 +435,102 @@ js.value(CCObject, 'Flags', { IsSizeLocked, }); +declare namespace CCObject { + export enum Flags { + Destroyed, + // ToDestroy: ToDestroy, + + /** + * @en The object will not be saved. + * @zh 该对象将不会被保存。 + */ + DontSave, + + /** + * @en The object will not be saved when building a player. + * @zh 构建项目时,该对象将不会被保存。 + */ + EditorOnly, + + Dirty, + + /** + * @en Dont destroy automatically when loading a new scene. + * @zh 加载一个新场景时,不自动删除该对象 + * @property DontDestroy + * @private + */ + DontDestroy, + + PersistentMask, + + // FLAGS FOR ENGINE + + Destroying, + + /** + * @en The node is deactivating. + * @zh 节点正在反激活的过程中。 + * @private + */ + Deactivating, + + /** + * @en The lock node, when the node is locked, cannot be clicked in the scene. + * @zh 锁定节点,锁定后场景内不能点击 + * @private + */ + LockedInEditor, + + /// ** + // * @en + // * Hide in game and hierarchy. + // * This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). + // * @zh + // * 在游戏和层级中隐藏该对象。
+ // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 + // * @property {Number} HideInGame + // */ + // HideInGame: HideInGame, + + // FLAGS FOR EDITOR + + /// ** + // * @en This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). + // * @zh 该标记只读,它只能被用作 scene.addEntity()的一个参数。 + // */ + HideInHierarchy, + + /// ** + // * @en + // * Hide in game view, hierarchy, and scene view... etc. + // * This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). + // * @zh + // * 在游戏视图,层级,场景视图等等...中隐藏该对象。 + // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 + // */ + // Hide: Hide, + + //// UUID Registered in editor + // RegisteredInEditor: RegisteredInEditor, + + // FLAGS FOR COMPONENT + + IsPreloadStarted, + IsOnLoadStarted, + IsOnLoadCalled, + IsOnEnableCalled, + IsStartCalled, + IsEditorOnEnableCalled, + + IsPositionLocked, + IsRotationLocked, + IsScaleLocked, + IsAnchorLocked, + IsSizeLocked, + } +} + /* * @en * Checks whether the object is non-nil and not yet destroyed.
diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index b762c5974c..8bffac90dd 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -31,9 +31,8 @@ import { CCObject } from '../data/object'; import * as js from '../utils/js'; import { EDITOR, DEV, TEST } from 'internal:constants'; import { legacyCC } from '../global-exports'; -import { error, errorID } from '../platform/debug'; +import { error, errorID, getError } from '../platform/debug'; -// @ts-ignore const Destroying = CCObject.Flags.Destroying; export function baseNodePolyfill (BaseNode) { @@ -42,13 +41,11 @@ export function baseNodePolyfill (BaseNode) { const existing = this.getComponent(ctor._disallowMultiple); if (existing) { if (existing.constructor === ctor) { - errorID(3805, js.getClassName(ctor), this._name); + throw Error(getError(3805, js.getClassName(ctor), this._name)); } else { - errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); + throw Error(getError(3806, js.getClassName(ctor), this._name, js.getClassName(existing))); } - return false; } - return true; }; /** diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index d5bf4fc562..cf4d6b01c8 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -31,7 +31,7 @@ import { Component } from '../components/component'; import { ccclass, property } from '../data/class-decorator'; import { CCObject } from '../data/object'; import { Event } from '../event'; -import { errorID, warnID, error, log, assertID } from '../platform/debug'; +import { errorID, warnID, error, log, assertID, getError } from '../platform/debug'; import { SystemEventType } from '../platform/event-manager/event-enum'; import { ISchedulable } from '../scheduler'; import IdGenerator from '../utils/id-generator'; @@ -887,28 +887,29 @@ export class BaseNode extends CCObject implements ISchedulable { * @en Adds a component class to the node. You can also add component to node by passing in the name of the script. * @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 * @param classConstructor The class of the component to add + * @throws `TypeError` if the `classConstructor` does not specify a cc-class constructor extending the `Component`. * @example * ``` * var sprite = node.addComponent(SpriteComponent); * ``` */ - public addComponent (classConstructor: Constructor): T | null; + public addComponent (classConstructor: Constructor): T; /** * @en Adds a component class to the node. You can also add component to node by passing in the name of the script. * @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 * @param className The class name of the component to add + * @throws `TypeError` if the `className` does not specify a cc-class constructor extending the `Component`. * @example * ``` * var test = node.addComponent("Test"); * ``` */ - public addComponent (className: string): Component | null; + public addComponent (className: string): Component; public addComponent (typeOrClassName: string | Function) { if (EDITOR && (this._objFlags & Destroying)) { - error('isDestroying'); - return null; + throw Error(`isDestroying`); } // get component @@ -917,16 +918,14 @@ export class BaseNode extends CCObject implements ISchedulable { if (typeof typeOrClassName === 'string') { constructor = js.getClassByName(typeOrClassName); if (!constructor) { - errorID(3807, typeOrClassName); if (legacyCC._RF.peek()) { errorID(3808, typeOrClassName); } - return null; + throw TypeError(getError(3807, typeOrClassName)); } } else { if (!typeOrClassName) { - errorID(3804); - return null; + throw TypeError(getError(3804)); } constructor = typeOrClassName; } @@ -934,29 +933,21 @@ export class BaseNode extends CCObject implements ISchedulable { // check component if (typeof constructor !== 'function') { - errorID(3809); - return null; + throw TypeError(getError(3809)); } if (!js.isChildClassOf(constructor, legacyCC.Component)) { - errorID(3810); - return null; + throw TypeError(getError(3810)); } if (EDITOR && constructor._disallowMultiple) { - if (!this._checkMultipleComp!(constructor)) { - return null; - } + this._checkMultipleComp!(constructor); } // check requirement const ReqComp = constructor._requireComponent; if (ReqComp && !this.getComponent(ReqComp)) { - const depended = this.addComponent(ReqComp); - if (!depended) { - // depend conflicts - return null; - } + this.addComponent(ReqComp); } //// check conflict @@ -1407,7 +1398,12 @@ export class BaseNode extends CCObject implements ISchedulable { protected _onSiblingIndexChanged? (siblingIndex: number): void; - protected _checkMultipleComp? (constructor: Function): boolean; + /** + * Ensures that this node has already had the specified component(s). If not, this method throws. + * @param constructor Constructor of the component. + * @throws If one or more component of same type have been existed in this node. + */ + protected _checkMultipleComp? (constructor: Function): void; } baseNodePolyfill(BaseNode); diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index b36cc93b00..25135c0da3 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -29,12 +29,13 @@ import { ccclass, property } from '../data/class-decorator'; import { Mat4, Quat, Vec3 } from '../math'; -import { warnID, assert } from '../platform/debug'; +import { warnID, assert, getError } from '../platform/debug'; import { RenderScene } from '../renderer/scene/render-scene'; import { BaseNode } from './base-node'; import { SceneGlobals } from './scene-globals'; import { EDITOR, TEST } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { Component } from '../components/component'; /** * @en @@ -109,9 +110,8 @@ export class Scene extends BaseNode { * @en Only for compatibility purpose, user should not add any component to the scene * @zh 仅为兼容性保留,用户不应该在场景上直接添加任何组件 */ - public addComponent (typeOrClassName: string | Function) { - warnID(3822); - return null; + public addComponent (typeOrClassName: string | Function): Component { + throw new Error(getError(3822)); } public _onHierarchyChanged () { }