より良いエンジニアを目指して

1日1つ。良くなる!上手くなる!

Cloud Functionsをデプロイしたが「OperationError: code=3, message=Function failed on loading user code.」

Cloud Functionsにデプロイしようとしたものの、

ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs

というエラーに悩まされた話です。

const escapeHtml = require('escape-html');

/**
 * Responds to an HTTP request using data from the request body parsed according
 * to the "content-type" header.
 *
 * @param {Object} req Cloud Function request context.
 * @param {Object} res Cloud Function response context.
 */
exports.helloContent = (req, res) => {
  let name;

  switch (req.get('content-type')) {
    // '{"name":"John"}'
    case 'application/json':
      ({name} = req.body);
      break;

    // 'John', stored in a Buffer
    case 'application/octet-stream':
      name = req.body.toString(); // Convert buffer to a string
      break;

    // 'John'
    case 'text/plain':
      name = req.body;
      break;

    // 'name=John' in the body of a POST request (not the URL)
    case 'application/x-www-form-urlencoded':
      ({name} = req.body);
      break;
  }

  res.status(200).send(`Hello ${escapeHtml(name || 'World')}!`);
};

これは公式ドキュメントのサンプルコードなのですが、あまり何も考えず

  1. npm init
  2. サンプルコードをコピペしてindex.jsを作成
  3. gloud コマンドでデプロイ

すると、以下のようなエラーになってしまいます。

ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function failed on loading user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs

この場合、package.jsonにescape-htmlが宣言されていないことが問題です。

npm install escape-html

が必要ですね。

これでは、わかりづらいので調査が大変です。