오류 처리
Handle errors in your modules using error codes and custom error-handling logic.
읽는 시간 2분최근 업데이트: 한 달 전
모듈에서 오류를 처리하는 방법을 알아봅니다.
오류 코드
모듈에서 예외가 발생하면 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>로깅
모듈 디버깅에 도움이 되도록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");