오류 처리
스크립트에서 오류를 처리하는 방법을 알아봅니다.
오류 코드
스크립트에서 예외가 발생하면 Cloud Code는 422
상태 오류를 반환합니다.
오류 처리 로직에는 Cloud Code API 오류 응답에서 반환된 오류 메시지가 아니라 오류 코드 또는 오류 유형을 사용하십시오. 오류 메시지는 향후 변경될 수 있지만 오류 코드와 유형은 동일하게 유지됩니다.
오류 래핑
오류를 처리하려면 코드를 try/catch
블록으로 래핑합니다. 오류가 발생하면 이를 로깅하여 클라이언트로 오류를 반환할 수 있습니다.
래핑되지 않은 함수를 사용하는 경우를 예로 들어 보겠습니다.
JavaScript
const { CurrenciesApi } = require("@unity-services/economy-2.4");
module.exports = async ({ params, context, logger }) => {
const { projectId, playerId } = context;
const { currencyId } = params;
const currencies = new CurrenciesApi(context);
const setBalance = await currencies.setPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyBalanceRequest: { balance: 100 } });
const decrement = await currencies.decrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 50 } });
const increment = await currencies.incrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 10 } });
const result = await currencies.getPlayerCurrencies({ projectId, playerId });
return result.data;
}
래핑되지 않은 함수는 API 호출 중 하나라도 실패하면 오류를 반환합니다. 하지만 API 호출을 래핑하면 오류 메시지를 로깅하고 오류를 더욱 자세히 알아볼 수 있습니다.
JavaScript
const { CurrenciesApi } = require("@unity-services/economy-2.4");
module.exports = async ({ params, context, logger }) => {
const { projectId, playerId } = context;
const { currencyId } = params;
const currencies = new CurrenciesApi(context);
try {
const setBalance = await currencies.setPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyBalanceRequest: { balance: 100 } });
const decrement = await currencies.decrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 50 } });
const increment = await currencies.incrementPlayerCurrencyBalance({ projectId, playerId, currencyId, currencyModifyBalanceRequest: { amount: 10 } });
const result = await currencies.getPlayerCurrencies({ projectId, playerId });
return result.data;
} catch (err) {
logger.error("Failed to increment currency", {"error.message": err.message}, {"currencyId" : currencyId});
throw err;
}
}
Unity Dashboard에서 로그를 확인할 수 있습니다. 오류에 대한 자세한 내용을 알아보려면 Live Ops > Cloud Code > Logs를 선택합니다.
로깅
스크립트 디버깅에 도움이 되도록 logger
오브젝트를 사용하여 오류와 경고를 로깅할 수 있습니다. 다양한 심각도 레벨로 메시지를 로깅할 수 있습니다. 이러한 레벨은 Unity Dashboard에서 로그를 쿼리하는 데 도움이 될 수 있습니다.
Cloud Code에서 playerId
, environmentId
, projectId
등의 속성을 자동으로 로그에 추가하므로 로그 메시지에 직접 추가할 필요가 없습니다.
JavaScript
logger.debug(message, ...logAttributes)
logger.info(message, ...logAttributes)
logger.warning(message, ...logAttributes)
logger.error(message, ...logAttributes)
logger.fatal(message, ...logAttributes)
커스텀 로그 속성을 추가하여 로그 메시지에 대한 자세한 컨텍스트를 확인할 수 있습니다. 예를 들어, Economy에 대한 호출이 실패하는 경우 로그 메시지에 currencyId
를 추가할 수 있습니다.
JavaScript
logger.error("Failed to increment currency", {"error.message": err.message}, {"currencyId" : params.currencyId});
로그를 보고 필터링하려면 Unity Dashboard로 이동하여 Live Ops > Cloud Code > Logs를 선택합니다.
자세한 내용은 로그 내보내기를 참고하십시오.
Unity Dashboard에서의 디버깅
Unity Dashboard를 통해 스크립트를 디버깅할 수 있습니다.
Live Ops > Cloud Code > Scripts로 이동하여 디버깅할 스크립트를 선택합니다.
Response 탭과 스크립트 에디터 도움말에 오류가 발생한 위치가 표시됩니다.
Response 탭에는 오류의 행과 열이 표시됩니다. 디버거는 이 정보를 사용하여 Script Code 섹션에 오류가 발생한 위치를 시각적으로 나타내는 주석을 추가합니다.
오류 주석은 스크립트를 편집하거나 다시 실행할 때까지 계속 표시됩니다.
다음은 오류를 처리하고 발생시키는 방법의 예시입니다.
JavaScript
const { CurrenciesApi } = require("@unity-services/economy-2.4");
module.exports = async ({ params, context, logger }) => {
const { playerId, projectId } = context;
const { currencyId } = params;
const currencies = new CurrenciesApi(context);
try {
const setBalance = await currencies.setPlayerCurrencyBalance({
projectId,
playerId,
currencyId,
currencyBalanceRequest: {
balance: 100,
}
});
} catch (err) {
if (err.response) {
logger.error("Failed to set currency", { "error.response": err.response }, {"currencyId": currencyId});
} else {
logger.error("Failed to set currency", { "error.message": err.message }, {"currencyId": currencyId});
}
throw Error('oops');
}
}