错误处理
Handle errors in your modules using error codes and custom error-handling logic.
阅读时间3 分钟最后更新于 1 个月前
了解如何处理模块中的错误。
错误代码
如果模块抛出异常,Cloud Code 将返回422对错误进行包装
请将代码包装在trycatch这个未包装的函数返回一般错误:[CloudCodeFunction("IncrementBalance")]public async Task<ApiResponse<CurrencyBalanceResponse>> IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, string currencyId){ return await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.ServiceToken, ctx.ProjectId, ctx.PlayerId, currencyId, new CurrencyModifyBalanceRequest(currencyId, 10));}
如果添加{ "type": "problems/invocation", "title": "Unprocessable Entity", "status": 422, "detail": "Invocation Error", "instance": null, "code": 9009, "details": [ { "message": "Error executing Cloud Code function. Exception type: ApiException. Message: Bad Request", "name": "ScriptRunner.Exceptions.CloudCodeRuntimeException", "stackTrace": [ "at Unity.Services.CloudCode.Shared.HttpApiClient.ToApiResponse[T](HttpResponseMessage response)", "at Unity.Services.CloudCode.Shared.HttpApiClient.SendAsync[T](String path, HttpMethod method, ApiRequestOptions options, IApiConfiguration configuration, CancellationToken cancellationToken)", "at Unity.Services.Economy.Api.EconomyCurrenciesApi.IncrementPlayerCurrencyBalanceAsync(IExecutionContext executionContext, String accessToken, String projectId, String playerId, String currencyId, CurrencyModifyBalanceRequest currencyModifyBalanceRequest, String configAssignmentHash, String unityInstallationId, String analyticsUserId, CancellationToken cancellationToken)", "at Sample.HelloWorld.IncrementBalanceUnhandled(IGameApiClient gameApiClient, IExecutionContext ctx, String currencyId) in Sample/Main/HelloWorld.cs:line 148" ] } ]}
trycatch以下已包装的函数返回一条包含更多详细信息的错误消息:[CloudCodeFunction("IncrementBalance")]public async Task<ApiResponse<CurrencyBalanceResponse>> IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, string currencyId){ try { return await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.ServiceToken, ctx.ProjectId, ctx.PlayerId, currencyId, new CurrencyModifyBalanceRequest(currencyId, 10)); } catch (ApiException e) { _logger.LogError("Failed to increment {currencyId} balance for the player. Error: {error}", currencyId, e.Message); throw new Exception($"Failed to increment balance for playerId {ctx.PlayerId}. Error: {e.Message}"); }}
您可以在 Unity Cloud Dashboard 中查看日志。要获取更多有关该错误的详细信息,请选择 Products(产品)> Cloud Code > Logs(日志)。{ "type": "problems/invocation", "title": "Unprocessable Entity", "status": 422, "detail": "Invocation Error", "instance": null, "code": 9009, "details": [ { "message": "Error executing Cloud Code function. Exception type: Exception. Message: Failed to increment balance for playerId 7wCG6G0d1PU6WSVZPG9oQ1op97xd. Error: Bad Request", "name": "ScriptRunner.Exceptions.CloudCodeRuntimeException", "stackTrace": [ "at Sample.HelloWorld.IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, String currencyId) in Sample/Main/HelloWorld.cs:line 165" ] } ]}
批处理请求的错误处理
如需了解有关批处理请求的更多信息,请参阅批处理请求。状态代码
每当 Cloud Code C# SDK 返回不成功的状态代码时,该 SDK 都会抛出ApiExceptionApiExceptionApiResponse未处理的错误
Cloud Code 无法处理因内存泄漏导致的异常,例如无限循环。如果您的模块超出了内存限制,工作线程最终会崩溃。Cloud Code 无法处理async voidTaskTask<T>Logging
为了帮助您调试模块,您可以使用ILoggerplayerIdenvironmentIdprojectId您可以记录不同级别的消息。这些级别可以帮助您在 Unity Cloud Dashboard 中查询日志。public class HelloWorld{ private readonly ILogger<HelloWorld> _logger; public HelloWorld(ILogger<HelloWorld> logger) { _logger = logger; } [CloudCodeFunction("IncrementBalance")] public async Task<ApiResponse<CurrencyBalanceResponse>> IncrementPlayerBalance(IGameApiClient gameApiClient, IExecutionContext ctx, string currencyId) { try { var res = await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.ServiceToken, ctx.ProjectId, ctx.PlayerId, currencyId, new CurrencyModifyBalanceRequest(currencyId, 10)); _logger.LogInformation("Incremented currency {currencyId} balance by {amount}", currencyId, 10); return res; } catch (ApiException e) { _logger.LogError("Failed to increment {currencyId} balance for the player. Error: {error}", currencyId, e.Message); throw new Exception($"Failed to increment balance for playerId {ctx.PlayerId}. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
要查看和过滤日志,请导航到 Unity Cloud Dashboard 并选择 Products(产品) > Cloud Code > Logs(日志)。 如需了解更多信息,请参阅发出日志。_logger.LogDebug("debug message");_logger.LogInformation("info message");_logger.LogWarning("warning message");_logger.LogError("error message");_logger.LogCritical("critical message");