# 错误处理

> Handle errors in your scripts using error codes and custom error-handling logic.

了解如何处理脚本中的错误。

## 错误代码##error-codes

如果脚本抛出异常，Cloud Code 将返回 `422` 状态错误。

对于错误处理逻辑，请使用从 Cloud Code API 错误响应返回的错误代码或错误类型，而不是错误消息。错误消息将来可能会更改，但错误代码和类型会保持不变。

## 对错误进行包装##error-wrapping

请将代码包装在 `try/catch` 代码块中来处理错误。如果发生错误，您可以记录该错误并向客户端返回一个错误。

例如，您可以使用一个未包装的函数：

### JavaScript##javascript

```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##javascript

```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](https://cloud.unity.com)，然后选择 **Products（产品）**> **Cloud Code** > **Logs（日志）**。

## Logging##logging

您可以使用 `logger` 对象来记录错误和警告，以帮助您调试脚本。您可以记录不同严重级别的消息。这些级别可以帮助您在 Unity Dashboard 中查询日志。

Cloud Code 会自动将 `playerId`、`environmentId` 和 `projectId` 等属性添加到日志中，因此您无需将它们添加到日志消息中。

### JavaScript##javascript

```javascript
logger.debug(message, ...logAttributes)
logger.info(message, ...logAttributes)
logger.warning(message, ...logAttributes)
logger.error(message, ...logAttributes)
logger.fatal(message, ...logAttributes)
```

您可以添加自定义日志属性来获取有关日志消息的更多上下文。例如，当调用 Economy 失败时，可以将 `currencyId` 添加到日志消息中：

### JavaScript##javascript

```javascript
logger.error("Failed to increment currency", {"error.message": err.message}, {"currencyId" : params.currencyId});
```

导航到 [Unity Dashboard](https://cloud.unity.com) 并选择 **Cloud Code** > **Logs（日志）** 以查看和过滤日志。

请参阅[发出日志](../../logging/tutorials/emit-logs#cloud-code-javascript-scripts)以获取更多信息。

## 在 Unity Dashboard 上进行调试##debugging-on-the-unity-dashboard

您可以通过 [Unity Dashboard](https://cloud.unity.com) 调试您的脚本。

导航到 **Cloud Code** > **Scripts（脚本）**，然后选择要调试的脚本。

Response（响应）选项卡和脚本编辑器可帮助指出发生错误的位置。

Response（响应）选项卡会显示错误的行和列。调试器会使用此信息，并在 Script Code（脚本代码）部分中添加批注以直观的形式指出发生错误的位置。


**Frame:**
![](/api/media?file=/cloud-code/media/images/cloud-code-debugging.png)

错误批注将保持可见状态，直到您编辑脚本或再次运行脚本。

以下示例显示了如何处理和抛出错误。

### JavaScript##javascript

```js
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');
  }

}
```
