perf : 异常处理替换为YOO的异常类

This commit is contained in:
何冠峰
2025-12-05 15:45:04 +08:00
parent 5da8c6baf8
commit e5d0a856a5
27 changed files with 243 additions and 74 deletions

View File

@@ -87,11 +87,11 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (Exception e)
catch (Exception ex)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load catalog file : {e.Message}";
Error = $"Failed to load catalog file : {ex.Message}";
}
}
}

View File

@@ -499,7 +499,7 @@ namespace YooAsset
{
if (_records.ContainsKey(bundle.BundleGUID))
{
throw new Exception("Should never get here !");
throw new YooInternalException();
}
string infoFilePath = GetBundleInfoFilePath(bundle);
@@ -521,9 +521,9 @@ namespace YooAsset
// 写入文件信息
WriteBundleInfoFile(infoFilePath, bundle.FileCRC, bundle.FileSize);
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Error($"Failed to write cache file ! {e.Message}");
YooLogger.Error($"Failed to write cache file ! {ex.Message}");
return false;
}

View File

@@ -37,9 +37,9 @@ namespace YooAsset
return false;
}
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Error($"Failed to delete cache file ! {e.Message}");
YooLogger.Error($"Failed to delete cache file ! {ex.Message}");
return false;
}
}

View File

@@ -33,9 +33,9 @@ namespace YooAsset
{
Directory.Delete(FileRootPath, true);
}
catch (System.Exception e)
catch (System.Exception ex)
{
YooLogger.Warning($"Failed to delete cache bundle folder : {e}");
YooLogger.Warning($"Failed to delete cache bundle folder : {ex}");
}
}
}

View File

@@ -320,11 +320,11 @@ namespace YooAsset
File.Move(recordFileElement.DataFilePath, filePath);
_steps = ESteps.LoadCacheRawBundle;
}
catch (Exception e)
catch (Exception ex)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Faild rename raw data file : {e.Message}";
Error = $"Faild rename raw data file : {ex.Message}";
}
}
else

View File

@@ -142,7 +142,7 @@ namespace YooAsset
PackageName = packageName;
if (string.IsNullOrEmpty(packageRoot))
throw new Exception($"{nameof(DefaultEditorFileSystem)} root directory is null or empty !");
throw new YooFileSystemException($"{nameof(DefaultEditorFileSystem)} package root is null or empty !");
_packageRoot = packageRoot;
}

View File

@@ -81,11 +81,11 @@ namespace YooAsset
_steps = ESteps.Done;
Status = EOperationStatus.Succeed;
}
catch (Exception e)
catch (Exception ex)
{
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = $"Failed to load catalog file : {e.Message}";
Error = $"Failed to load catalog file : {ex.Message}";
}
}
}

View File

@@ -133,7 +133,7 @@ namespace YooAsset
{
#if UNITY_EDITOR
if (Childs.Contains(child))
throw new Exception($"The child node {child.GetType().Name} already exists !");
throw new YooInternalException($"The child node {child.GetType().Name} already exists !");
#endif
Childs.Add(child);

View File

@@ -36,7 +36,7 @@ namespace YooAsset
{
public static PackageInvokeBuildResult InvokeBuilder(PackageInvokeBuildParam buildParam)
{
throw new System.Exception("Only support in unity editor platform !");
throw new YooPlatformNotSupportedException("This feature is only supported in Unity Editor platform.");
}
}
}

View File

@@ -22,7 +22,7 @@ namespace YooAsset
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
throw new YooHandleException($"{nameof(AllAssetsHandle)} is invalid. It may have been released or the provider was destroyed.");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -31,7 +31,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AllAssetsHandle)} is invalid");
throw new YooHandleException($"{nameof(AllAssetsHandle)} is invalid. It may have been released or the provider was destroyed.");
_callback -= value;
}
}

View File

@@ -22,7 +22,7 @@ namespace YooAsset
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetHandle)} is invalid");
throw new YooHandleException($"{nameof(AssetHandle)} is invalid. It may have been released or the provider was destroyed.");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -31,7 +31,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(AssetHandle)} is invalid");
throw new YooHandleException($"{nameof(AssetHandle)} is invalid. It may have been released or the provider was destroyed.");
_callback -= value;
}
}

View File

@@ -21,7 +21,7 @@ namespace YooAsset
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileHandle)} is invalid");
throw new YooHandleException($"{nameof(RawFileHandle)} is invalid. It may have been released or the provider was destroyed.");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -30,7 +30,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(RawFileHandle)} is invalid");
throw new YooHandleException($"{nameof(RawFileHandle)} is invalid. It may have been released or the provider was destroyed.");
_callback -= value;
}
}

View File

@@ -23,7 +23,7 @@ namespace YooAsset
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneHandle)} is invalid !");
throw new YooHandleException($"{nameof(SceneHandle)} is invalid. It may have been released or the provider was destroyed.");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -32,7 +32,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SceneHandle)} is invalid !");
throw new YooHandleException($"{nameof(SceneHandle)} is invalid. It may have been released or the provider was destroyed.");
_callback -= value;
}
}

View File

@@ -22,7 +22,7 @@ namespace YooAsset
add
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
throw new YooHandleException($"{nameof(SubAssetsHandle)} is invalid. It may have been released or the provider was destroyed.");
if (Provider.IsDone)
value.Invoke(this);
else
@@ -31,7 +31,7 @@ namespace YooAsset
remove
{
if (IsValidWithWarning == false)
throw new System.Exception($"{nameof(SubAssetsHandle)} is invalid");
throw new YooHandleException($"{nameof(SubAssetsHandle)} is invalid. It may have been released or the provider was destroyed.");
_callback -= value;
}
}

View File

@@ -166,10 +166,10 @@ namespace YooAsset
// 注意:正在加载中的任务不可以销毁
if (_steps == ESteps.LoadBundleFile)
throw new Exception($"Bundle file loader is not done : {LoadBundleInfo.Bundle.BundleName}");
throw new YooInternalException($"Cannot destroy loader while loading bundle : {LoadBundleInfo.Bundle.BundleName}");
if (RefCount > 0)
throw new Exception($"Bundle file loader ref is not zero : {LoadBundleInfo.Bundle.BundleName}");
throw new YooInternalException($"Cannot destroy loader with non-zero ref count {RefCount} : {LoadBundleInfo.Bundle.BundleName}");
if (Result != null)
Result.UnloadBundleFile();

View File

@@ -265,18 +265,18 @@ namespace YooAsset
public void ReleaseHandle(HandleBase handle)
{
if (RefCount <= 0)
throw new System.Exception("Should never get here !");
throw new YooInternalException($"Attempting to release handle when RefCount is already zero. Asset : {MainAssetInfo.AssetPath}");
if (_resManager.UseWeakReferenceHandle)
{
// TODO 高危风险:如果移除弱引用失败,会导致资源永远无法释放。
if (RemoveWeakReference(handle) == false)
throw new System.Exception("Should never get here !");
throw new YooInternalException($"Handle not found in weak reference list. Asset: {MainAssetInfo.AssetPath}");
}
else
{
if (_handles.Remove(handle) == false)
throw new System.Exception("Should never get here !");
throw new YooInternalException($"Handle not found in cache list. Asset: {MainAssetInfo.AssetPath}");
}
// 引用计数减少
@@ -385,7 +385,7 @@ namespace YooAsset
}
if (status.TotalBytes == 0)
throw new System.Exception("Should never get here !");
throw new YooInternalException("Download total size can not be zero.");
status.IsDone = status.DownloadedBytes == status.TotalBytes;
status.Progress = (float)status.DownloadedBytes / status.TotalBytes;

View File

@@ -102,7 +102,7 @@ namespace YooAsset
internal AssetInfo(string packageName, PackageAsset packageAsset, System.Type assetType)
{
if (packageAsset == null)
throw new System.Exception("Should never get here !");
throw new YooInternalException("Package asset can not be null.");
_providerGUID = string.Empty;
_packageAsset = packageAsset;

View File

@@ -115,9 +115,9 @@ namespace YooAsset
// 检测配置
if (Manifest.EnableAddressable && Manifest.LocationToLower)
throw new System.Exception("Addressable not support location to lower !");
throw new YooManifestException("Addressable not support location to lower !");
if (Manifest.EnableAddressable == false && Manifest.ReplaceAssetPathWithAddress)
throw new System.Exception("Replace asset path with address need enable Addressable !");
throw new YooManifestException("Replace asset path with address need enable Addressable !");
_steps = ESteps.PrepareAssetList;
}
@@ -216,12 +216,12 @@ namespace YooAsset
Status = EOperationStatus.Succeed;
}
}
catch (System.Exception e)
catch (System.Exception ex)
{
Manifest = null;
_steps = ESteps.Done;
Status = EOperationStatus.Failed;
Error = e.Message;
Error = ex.Message;
}
}
internal override void InternalWaitForAsyncComplete()
@@ -266,7 +266,7 @@ namespace YooAsset
// 注意:我们不允许原始路径存在重名
string assetPath = packageAsset.AssetPath;
if (manifest.AssetDic.ContainsKey(assetPath))
throw new System.Exception($"AssetPath have existed : {assetPath}");
throw new YooManifestException($"AssetPath have existed : {assetPath}");
else
manifest.AssetDic.Add(assetPath, packageAsset);
@@ -276,7 +276,7 @@ namespace YooAsset
// 添加原生路径的映射
if (manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Location have existed : {location}");
throw new YooManifestException($"Location have existed : {location}");
else
manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
@@ -298,7 +298,7 @@ namespace YooAsset
if (manifest.IncludeAssetGUID)
{
if (manifest.AssetPathMapping2.ContainsKey(packageAsset.AssetGUID))
throw new System.Exception($"AssetGUID have existed : {packageAsset.AssetGUID}");
throw new YooManifestException($"AssetGUID have existed : {packageAsset.AssetGUID}");
else
manifest.AssetPathMapping2.Add(packageAsset.AssetGUID, packageAsset.AssetPath);
}
@@ -310,7 +310,7 @@ namespace YooAsset
if (string.IsNullOrEmpty(location) == false)
{
if (manifest.AssetPathMapping1.ContainsKey(location))
throw new System.Exception($"Location have existed : {location}");
throw new YooManifestException($"Location have existed : {location}");
else
manifest.AssetPathMapping1.Add(location, packageAsset.AssetPath);
}

View File

@@ -76,7 +76,7 @@ namespace YooAsset
get
{
if (string.IsNullOrEmpty(_fileName))
throw new Exception("Should never get here !");
throw new YooInternalException("File name can not be null or empty.");
return _fileName;
}
}
@@ -90,7 +90,7 @@ namespace YooAsset
get
{
if (string.IsNullOrEmpty(_fileExtension))
throw new Exception("Should never get here !");
throw new YooInternalException("File extension can not be null or empty.");
return _fileExtension;
}
}

View File

@@ -134,7 +134,7 @@ namespace YooAsset
}
else
{
throw new Exception($"Invalid bundle id : {bundleID} Asset path : {packageAsset.AssetPath}");
throw new YooManifestException($"Invalid bundle ID : {bundleID}. Valid range is 0 to {BundleList.Count - 1}");
}
}
@@ -196,11 +196,13 @@ namespace YooAsset
if (bundleID >= 0 && bundleID < BundleList.Count)
{
var packageBundle = BundleList[bundleID];
if (packageBundle == null)
throw new YooInternalException();
return packageBundle;
}
else
{
throw new Exception($"Invalid bundle id : {bundleID}");
throw new YooManifestException($"Invalid bundle ID : {bundleID}. Valid range is 0 to {BundleList.Count - 1}");
}
}

View File

@@ -156,7 +156,7 @@ namespace YooAsset
private BundleInfo CreateBundleInfo(PackageBundle packageBundle)
{
if (packageBundle == null)
throw new Exception("Should never get here !");
throw new YooInternalException();
var fileSystem = GetBelongFileSystem(packageBundle);
if (fileSystem != null)
@@ -165,12 +165,12 @@ namespace YooAsset
return bundleInfo;
}
throw new Exception($"Can not found belong file system : {packageBundle.BundleName}");
throw new YooFileSystemException($"Can not found belong file system : {packageBundle.BundleName}");
}
BundleInfo IBundleQuery.GetMainBundleInfo(AssetInfo assetInfo)
{
if (assetInfo == null || assetInfo.IsInvalid)
throw new Exception("Should never get here !");
throw new YooInternalException();
// 注意:如果清单里未找到资源包会抛出异常!
var packageBundle = ActiveManifest.GetMainPackageBundle(assetInfo.Asset);
@@ -179,7 +179,7 @@ namespace YooAsset
List<BundleInfo> IBundleQuery.GetDependBundleInfos(AssetInfo assetInfo)
{
if (assetInfo == null || assetInfo.IsInvalid)
throw new Exception("Should never get here !");
throw new YooInternalException();
// 注意:如果清单里未找到资源包会抛出异常!
List<PackageBundle> depends;

View File

@@ -152,19 +152,19 @@ namespace YooAsset
private void CheckInitializeParameters(InitializeParameters parameters)
{
if (_isInitialize)
throw new Exception($"{nameof(ResourcePackage)} is initialized yet.");
throw new YooPackageException(PackageName, $"Package '{PackageName}' is already initialized !");
if (parameters == null)
throw new Exception($"{nameof(ResourcePackage)} create parameters is null.");
throw new YooPackageException(PackageName, $"Initialize parameters cannot be null.");
#if !UNITY_EDITOR
if (parameters is EditorSimulateModeParameters)
throw new Exception($"Editor simulate mode only support unity editor.");
throw new YooPlatformNotSupportedException($"Editor simulate mode only support unity editor.");
#endif
// 检测初始化参数
if (parameters.BundleLoadingMaxConcurrency <= 0)
throw new Exception($"{nameof(parameters.BundleLoadingMaxConcurrency)} value must be greater than zero.");
throw new YooPackageException(PackageName, $"{nameof(parameters.BundleLoadingMaxConcurrency)} value must be greater than zero.");
// 鉴定运行模式
if (parameters is EditorSimulateModeParameters)
@@ -186,12 +186,12 @@ namespace YooAsset
#if UNITY_WEBGL
if (_playMode != EPlayMode.WebPlayMode)
{
throw new Exception($"{_playMode} can not support WebGL plateform !");
throw new YooPlatformNotSupportedException($"{_playMode} can not support WebGL plateform !");
}
#else
if (_playMode == EPlayMode.WebPlayMode)
{
throw new Exception($"{nameof(EPlayMode.WebPlayMode)} only support WebGL plateform !");
throw new YooPlatformNotSupportedException($"{nameof(EPlayMode.WebPlayMode)} only support WebGL plateform !");
}
#endif
}
@@ -1158,14 +1158,14 @@ namespace YooAsset
private void DebugCheckInitialize(bool checkActiveManifest = true)
{
if (_initializeStatus == EOperationStatus.None)
throw new Exception("Package initialize not completed !");
throw new YooPackageException(PackageName, "Package initialize not completed !");
else if (_initializeStatus == EOperationStatus.Failed)
throw new Exception($"Package initialize failed ! {_initializeError}");
throw new YooPackageException(PackageName, $"Package initialize failed ! {_initializeError}");
if (checkActiveManifest)
{
if (_playModeImpl.ActiveManifest == null)
throw new Exception("Can not found active package manifest !");
throw new YooPackageException(PackageName, "Can not found active package manifest !");
}
}
@@ -1177,12 +1177,12 @@ namespace YooAsset
if (typeof(UnityEngine.Behaviour).IsAssignableFrom(type))
{
throw new Exception($"Load asset type is invalid : {type.FullName} !");
throw new YooLoadException($"Load asset type is invalid : {type.FullName} !");
}
if (typeof(UnityEngine.Object).IsAssignableFrom(type) == false)
{
throw new Exception($"Load asset type is invalid : {type.FullName} !");
throw new YooLoadException($"Load asset type is invalid : {type.FullName} !");
}
}
#endregion

View File

@@ -0,0 +1,156 @@
using System;
namespace YooAsset
{
/// <summary>
/// YooAsset 异常基类
/// </summary>
[Serializable]
public class YooException : Exception
{
public YooException() : base() { }
public YooException(string message) : base(message) { }
public YooException(string message, Exception inner) : base(message, inner) { }
}
/// <summary>
/// 内部错误异常
/// 当发生不应该发生的内部错误时抛出(通常表示代码逻辑错误)
/// 这类异常通常表示需要修复代码,而不是用户使用错误
/// </summary>
[Serializable]
public class YooInternalException : YooException
{
public YooInternalException() : base($"Internal error (should never happen)") { }
public YooInternalException(string message) : base($"Internal error (should never happen) {message}") { }
public YooInternalException(Exception inner) : base($"Internal error (should never happen)", inner) { }
public YooInternalException(string message, Exception inner) : base($"Internal error (should never happen) {message}", inner) { }
}
/// <summary>
/// 初始化相关异常
/// 当 YooAsset 系统初始化失败或未初始化时访问功能时抛出
/// </summary>
[Serializable]
public class YooInitializeException : YooException
{
public YooInitializeException() : base() { }
public YooInitializeException(string message) : base(message) { }
public YooInitializeException(string message, Exception inner) : base(message, inner) { }
}
/// <summary>
/// 平台不支持异常
/// 当功能在当前平台不支持时抛出
/// </summary>
[Serializable]
public class YooPlatformNotSupportedException : YooException
{
public YooPlatformNotSupportedException() : base()
{
}
public YooPlatformNotSupportedException(string message) : base(message)
{
}
public YooPlatformNotSupportedException(string message, Exception inner) : base(message, inner) { }
}
/// <summary>
/// 包裹管理异常
/// 当包裹创建、销毁、初始化等操作失败时抛出
/// </summary>
[Serializable]
public class YooPackageException : YooException
{
/// <summary>
/// 包裹名称
/// </summary>
public string PackageName { get; }
public YooPackageException(string packageName) : base()
{
PackageName = packageName;
}
public YooPackageException(string packageName, string message) : base(message)
{
PackageName = packageName;
}
public YooPackageException(string packageName, string message, Exception inner) : base(message, inner)
{
PackageName = packageName;
}
}
/// <summary>
/// 资源清单文件异常
/// 当资源清单加载、数据无效或损坏时抛出
/// </summary>
[Serializable]
public class YooManifestException : YooException
{
public YooManifestException() : base()
{
}
public YooManifestException(string message) : base(message)
{
}
public YooManifestException(string message, Exception inner) : base(message, inner)
{
}
}
/// <summary>
/// 资源加载异常
/// 当资源加载类型不匹配时抛出
/// </summary>
[Serializable]
public class YooLoadException : YooException
{
public YooLoadException() : base()
{
}
public YooLoadException(string message) : base(message)
{
}
public YooLoadException(string message, Exception inner)
: base(message, inner)
{
}
}
/// <summary>
/// 资源句柄异常
/// 当句柄无效或操作句柄失败时抛出
/// </summary>
[Serializable]
public class YooHandleException : YooException
{
public YooHandleException() : base()
{
}
public YooHandleException(string message) : base(message)
{
}
public YooHandleException(string message, Exception inner) : base(message, inner)
{
}
}
/// <summary>
/// 文件系统异常
/// 当文件读写、验证、缓存操作失败时抛出
/// </summary>
[Serializable]
public class YooFileSystemException : YooException
{
public YooFileSystemException() : base()
{
}
public YooFileSystemException(string message) : base(message)
{
}
public YooFileSystemException(string message, Exception inner) : base(message, inner)
{
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ebd053b66fcf53a4a95863d5056c004f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -242,9 +242,9 @@ namespace YooAsset
{
return FileSHA1(filePath);
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Exception(e);
YooLogger.Exception(ex);
return string.Empty;
}
}
@@ -302,9 +302,9 @@ namespace YooAsset
{
return FileMD5(filePath);
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Exception(e);
YooLogger.Exception(ex);
return string.Empty;
}
}
@@ -372,9 +372,9 @@ namespace YooAsset
{
return FileCRC32(filePath);
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Exception(e);
YooLogger.Exception(ex);
return string.Empty;
}
}
@@ -384,9 +384,9 @@ namespace YooAsset
{
return FileCRC32Value(filePath);
}
catch (Exception e)
catch (Exception ex)
{
YooLogger.Exception(e);
YooLogger.Exception(ex);
return 0;
}
}

View File

@@ -117,7 +117,7 @@ namespace YooAsset
{
CheckException(packageName);
if (ContainsPackage(packageName))
throw new Exception($"Package {packageName} already existed !");
throw new YooPackageException(packageName, $"Package {packageName} already existed ! Cannot create duplicate packages.");
YooLogger.Log($"Create resource package : {packageName}");
ResourcePackage package = new ResourcePackage(packageName);
@@ -223,18 +223,18 @@ namespace YooAsset
private static void CheckException(string packageName)
{
if (_isInitialize == false)
throw new Exception($"{nameof(YooAssets)} not initialize !");
throw new YooInitializeException($"{nameof(YooAssets)} not initialized ! Please call {nameof(YooAssets.Initialize)} first.");
if (string.IsNullOrEmpty(packageName))
throw new Exception("Package name is null or empty !");
throw new YooInitializeException("Package name cannot be null or empty !");
}
private static void CheckException(ResourcePackage package)
{
if (_isInitialize == false)
throw new Exception($"{nameof(YooAssets)} not initialize !");
throw new YooInitializeException($"{nameof(YooAssets)} not initialized ! Please call {nameof(YooAssets.Initialize)} first.");
if (package == null)
throw new Exception("Package instance is null !");
throw new YooInitializeException("Package instance cannot be null !");
}
#region

View File

@@ -612,7 +612,7 @@ namespace YooAsset
private static void DebugCheckDefaultPackageValid()
{
if (_defaultPackage == null)
throw new Exception($"Default package is null. Please use {nameof(YooAssets.SetDefaultPackage)} !");
throw new YooInitializeException($"Default package is null. Please use {nameof(YooAssets.SetDefaultPackage)} !");
}
#endregion
}