arrow_back

App Dev - Debugging Application Errors: Node.js

登录 加入
访问 700 多个实验和课程

App Dev - Debugging Application Errors: Node.js

实验 2 个小时 universal_currency_alt 5 个积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
访问 700 多个实验和课程

Overview

In this lab, you leverage Cloud Debugger and Error Reporting to diagnose and fix errors in the running application.

Objectives

In this lab, you learn how to perform the following tasks:

  • Create a Cloud Source Repository and push application code to it.

  • Install and configure Cloud Debugger.

  • Use debug snapshots and logpoints to capture and display application variables.

  • Install and configure Cloud Error Reporting.

  • Leverage Cloud Error Reporting to identify application errors.

Setup and requirements

For each lab, you get a new Google Cloud project and set of resources for a fixed time at no cost.

  1. Sign in to Qwiklabs using an incognito window.

  2. Note the lab's access time (for example, 1:15:00), and make sure you can finish within that time.
    There is no pause feature. You can restart if needed, but you have to start at the beginning.

  3. When ready, click Start lab.

  4. Note your lab credentials (Username and Password). You will use them to sign in to the Google Cloud Console.

  5. Click Open Google Console.

  6. Click Use another account and copy/paste credentials for this lab into the prompts.
    If you use other credentials, you'll receive errors or incur charges.

  7. Accept the terms and skip the recovery resource page.

Activate Google Cloud Shell

Google Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud.

Google Cloud Shell provides command-line access to your Google Cloud resources.

  1. In Cloud console, on the top right toolbar, click the Open Cloud Shell button.

    Highlighted Cloud Shell icon

  2. Click Continue.

It takes a few moments to provision and connect to the environment. When you are connected, you are already authenticated, and the project is set to your PROJECT_ID. For example:

Project ID highlighted in the Cloud Shell Terminal

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  • You can list the active account name with this command:
gcloud auth list

Output:

Credentialed accounts: - @.com (active)

Example output:

Credentialed accounts: - google1623327_student@qwiklabs.net
  • You can list the project ID with this command:
gcloud config list project

Output:

[core] project =

Example output:

[core] project = qwiklabs-gcp-44776a13dea667a6 Note: Full documentation of gcloud is available in the gcloud CLI overview guide .

Task 1. Preparing the case study application

In this section, you access Cloud Shell, clone the git repository containing the quiz application, configure environment variables, and run the application.

Clone source code in Cloud Shell

  1. To clone the repository for the class, execute the following command:

git clone --depth=1 https://github.com/GoogleCloudPlatform/training-data-analyst
  1. Create a softlink as a shortcut in your working directory:

ln -s ~/training-data-analyst/courses/developingapps/v1.3/nodejs/stackdriver-debug-errorreporting ~/stackdriver-debug-errorreporting

Configure and run the case study application

  1. Change to the directory that contains the sample files for this lab:

cd ~/stackdriver-debug-errorreporting/start
  1. To configure the Quiz application, execute the following command:

. prepare_incomplete_environment.sh Note: This script file:

  • Creates an App Engine application.
  • Exports environment variables GCLOUD_PROJECT and GCLOUD_BUCKET.
  • Runs npm install.
  • Creates entities in Google Cloud Datastore.
  • Creates a Cloud Spanner instance.
  • Does NOT create a Google Cloud Pub/Sub topic.
  • Does NOT create a Cloud Spanner database.
  • Prints out the Google Cloud Project ID.

Task 2. Creating a Cloud Source Repository

In this section, you create a Cloud Source Repository and push the current lab's Quiz application code to it.

Create a Cloud Source Repository

  1. In the Cloud Console, on the Navigation menu, click Source Repositories.
  2. Click Add repository in the top right corner.
  3. Select Create new repository, and then click Continue.
  4. Name the repository default, and then for Project, select the project named with your GCP Project ID from the dropdown menu.
  5. Click Create.

The Add code to your repository dialog opens.

Clone the Repository

  1. Return to the Cloud Shell window.

  2. To change the working directory back to the home folder, execute the following command:

cd ~
  1. To clone the default Cloud Source Repository, execute the following command:

gcloud source repos clone default Note: Ignore the warning about cloning an empty repository.
  1. To copy the quiz application files from the lab folder into the repository, execute the following command:

cp -r ~/stackdriver-debug-errorreporting/start/quiz-app/* ~/default Note: The idea here is that you just want to simulate working on the Quiz application in the project's Cloud Source Repository.
  1. Change the working directory to the default directory:

cd ~/default
  1. Create a .gitignore file in the default folder to prevent the node_modules folder from being included in later git commands:

echo node_modules > .gitignore
  1. Enter the git command to add files to be committed:

git add .
  1. Enter the commands to configure git with your email and name:

git config --global user.email "student@example.com" git config --global user.name "A Student"
  1. Enter the git command to commit the changes with the message "Quiz application initial check-in":

git commit -m "Quiz application initial check-in"
  1. Enter the git command to push the changes into the default repository:

git push
  1. Return to the Source Repository window and refresh the browser tab.
Note: The Cloud Source Repositories window opens and shows the quiz application source code that you copied into the repository.

Task 3. Using Cloud Debugger

In this section, you write the code to create and start the Cloud Debugger in the quiz application and then set debug snapshots and logpoints in the Cloud Console.

Note: Update code within the sections marked as follows:

// TODO

// END TODO

To maximize your learning, review the code, inline comments, and related API documentation.

Write code to set up Cloud Debugger

  1. In Cloud Shell, to install the Node.js agent for Cloud Debugger, execute the following command:

cd ~/default npm install --save @google-cloud/debug-agent
  1. Click Open Editor.

If an error indicates that the code editor could not be loaded because third-party cookies are disabled, click Open in New Window and switch to the new tab.

  1. In the default/app.js file, import the '@google-cloud/debug-agent' module and then start it. Review the Setting Up Cloud Debugger for Node.js guide to learn more.

default/app.js

// TODO: Add the following statement to import and start // Stackdriver debug-agent // The start(...) method takes an 'options' object that you // can use to configure the Cloud Debugger agent. // You will need to pass through an object with an // allowExpressions Boolean property set to true. require('@google-cloud/debug-agent').start({ allowExpressions: true }); // END TODO
  1. Save the file.

Update the Cloud Source Repository and produce a source context

  1. Return to the Cloud Shell window.

If the Cloud Shell is not visible, click Open Terminal.

  1. To add, commit, and push the changes to the default Cloud Source Repository, execute the following commands:

cd ~/default git add . git commit -m "Added Cloud Debug Agent" git push
  1. To produce the source context file, execute the following command:

gcloud debug source gen-repo-info-file --output-directory . Note: This command creates the source-context.json file. This file allows Cloud Debugger to display the correct source code in the Cloud Console Debug window.

Debug the web application with a Snapshot

  1. To install the quiz application dependencies and start the application, execute the following command:

npm install npm start
  1. When you see App listening on port 8080, click Web preview > Preview on port 8080 to preview the quiz application.
  2. Return to the Cloud Console.
  3. On the Navigation menu, click Debugger.
Note: You should see that the source code for the application is displayed on the left-hand side of the Cloud Debug window.
  1. Use the source code navigator to select the web-app/questions.js file.
  2. Find the POST handler where questions are added (router.post('/add..)), and click the line number on the left-hand side of the blank statement just after let data = req.body. Click create snapshot.
Note: This inserts a snapshot into the source code. You should see in the right-hand panel that Cloud Debug is waiting for the snapshot to be hit.
  1. Return to the Quiz application and click Create Question.
  2. Fill in the form using the following values.

Form Field

Value

Author

Your Name

Quiz

Google Cloud

Title

Which are Google Cloud products?

Answer 1

Debug

Answer 2

Error Reporting

Answer 3

Logging

Answer 4

All of the above (Select answer 4 as correct!)

  1. Click Save.
  2. Return to the Cloud Debug window in the Cloud Console.
Note: Look at the right-hand panel.You should see that the snapshot has populated the Variables and Call Stack for the request.
  1. Expand the data variable.
Note: You should see the data that you entered into the form.

Debug the web application with a logpoint

  1. Still in questions.js, click on the Logpoint tab of the right panel in the Debug window.
  2. Click on the same source code line that you used to insert the snapshot and click create logpoint.
Note: This inserts a logpoint into the source code. An interactive editor opens where you can enter a statement that will be emitted to the application's logging output.
  1. In the logpoint interactive editor, write the following logging statement and click Add.

if (true) logpoint("Quiz = {data.quiz}")

This logging statement prints out the value of the quiz form field.

  1. Return to the Quiz application and, click Create Question.
  2. Fill in the form using the following values, and then click Save.

Form Field

Value

Author

Your Name

Quiz

Google Cloud

Title

Which Google Cloud product includes snapshots and logpoints?

Answer 1

Debugger (Select answer 1 as correct!)

Answer 2

Error Reporting

Answer 3

Logging

Answer 4

All of the above

  1. Return to the Cloud Shell window.
Note: You should see that the logpoint output is displayed in the form:

LOGPOINT: Quiz = 'gcp'

Task 4. Using Cloud Error Reporting

In this section, you write the code to integrate Cloud Error Reporting in the quiz application and observe errors from the web application and from Cloud Functions.

Write code to set up Cloud Error Reporting

  1. In Cloud Shell, to stop the web application, press Ctrl+C.

  2. To install the Node.js library for Cloud Error Reporting, execute the following command:

cd ~/default npm install --save @google-cloud/error-reporting
  1. In the Cloud Shell code editor, navigate to default/app.js.

  2. In the app.js file, load the '@google-cloud/error-reporting module.

  3. Create the Cloud Error Reporting client.

default/app.js

// TODO: Load the error-reporting module const {ErrorReporting} = require( '@google-cloud/error-reporting'); // END TODO const path = require('path'); const express = require('express'); const config = require('./config'); const app = express(); // TODO: Create the errorReporting client object const errorReporting = new ErrorReporting(); // END TODO
  1. Configure the application to use Cloud Error Reporting with Express.

default/app.js

// TODO: Use Stackdriver Error Reporting // middleware for Express app.use(errorReporting.express); // END TODO
  1. Save the file.

Update the Cloud Source Repository and produce a new source context

  1. Return to Cloud Shell window and execute the following commands to add, commit, and push the changes to the default Cloud Source Repository:

cd ~/default git add . git commit -m "Added Cloud Error Reporting" git push
  1. To produce source context file, execute the following command:

gcloud debug source gen-repo-info-file --output-directory . Note: This command updates the source-context.json file so that the source displayed by Error Reporting matches the executing application.

View web application errors using Error Reporting

  1. By default, Cloud Error Reporting is only active when the application is in production. Export an environment variable, NODE_ENV, with the value set to `production:

export NODE_ENV=production
  1. To start the application, execute the following command:

npm start
  1. Preview the web application.
  2. Return to the Cloud Console.
  3. On the Navigation menu, click Error Reporting.
Note: You should see that Error Reporting hasn't displayed any errors yet. Ignore the "Set up Error Reporting" button.
  1. Return to the quiz application, and click Take Test.
  2. Click Places.
  3. Complete the quiz, enter a rating and some feedback, and click Send Feedback.
Note: No 'Feedback Sent' response message is displayed.
  1. Return to the Cloud Console.
  2. On the Navigtion menu menu, click Error Reporting.
  3. Click Auto Reload.
Note: After a few seconds, an error message is displayed. In this case, the error was due to infrastructure misconfiguration. The Pub/Sub feedback topic was not created.

View Cloud Function errors using Error Reporting

  1. Return to Cloud Shell and stop the web application by pressing Ctrl+C.

  2. To create the missing Pub/Sub topic, execute the following command:

gcloud pubsub topics create feedback
  1. To create the Cloud Function that subscribes to the feedback topic and inserts a record into Cloud Spanner, execute the following commands:

cd ~/stackdriver-debug-errorreporting/start/ gcloud functions deploy process-feedback --runtime nodejs14 \ --trigger-topic feedback --source ./function \ --stage-bucket $GCLOUD_BUCKET --entry-point subscribe cd ~/default Note: It takes a few minutes to provision the Cloud Function.
  1. To start the web application, execute the following command:

npm start
  1. Preview the web application.
  2. Return to the quiz application, and click Take Test.
  3. Click Places.
  4. Complete the quiz, enter a rating and some feedback, and click Send Feedback.
Note: This time, Cloud Shell displays the 'Feedback Sent' response message.
  1. Return to the Cloud Console.
  2. On the Navigation menu, click Error Reporting.
Note: After a few seconds, a new error message is displayed. In this case, the error was also due to infrastructure misconfiguration. The Cloud Spanner database and Feedback table were not created.
  1. Click on the Error: ERROR processing feedback: link.
Note: This error was reported from the process-feedback Cloud Function. You will see the Error Reporting details for all the parts of the application.
  1. In the Recent samples section of the window, click on the View logs link for the Cloud Functions error.
Note: Cloud Functions errors automatically integrate with Cloud Logging. You should see an Error log item.
  1. To create the database and Feedback table, return to Cloud Shell, stop the web application, and then run the following command:

gcloud spanner databases create quiz-database --instance quiz-instance --ddl "CREATE TABLE Feedback ( feedbackId STRING(100) NOT NULL, email STRING(100), quiz STRING(20), feedback STRING(MAX), rating INT64, score FLOAT64, timestamp INT64 ) PRIMARY KEY (feedbackId);"

Task 5. Bonus: Finding a Logic Error in the Quiz application

In this section, you find an error in the Quiz application and use Cloud Debugger to identify the cause.

Reproduce the quiz application error

  1. Start the web application.
  2. Navigate to the Quiz application homepage and click Take Test.
  3. Click Places.
  4. Answer the question correctly.
  5. Click GCP, and then click Places again.
  6. Answer the question incorrectly.
  7. What score do you see?
Note: You should see that the score is wrong. The author included a logic error (on purpose of course!) somewhere in the application. Your job is to track it down. Note: Review

When using Cloud Debugger, which gcloud command do you use to specify the source code that is to be synchronized?

  1. gcloud compute instances create...
  2. gcloud app create...
  3. gcloud service-management create....
  4. gcloud debug source gen-repo-info-file...

What statements are true about Cloud Debugger snapshots?

  1. Snapshots capture all the local variables.
  2. Snapshots output data to logging output.
  3. Snapshots can include filters.
  4. Snapshots halt code execution on the running application.

When you use Cloud Error Reporting, how are errors integrated with Express?

  1. Add an error handler to Express, and invoke the Error Reporting client object's reportError(...) method.
  2. Register the Error Reporting client's express handler with Express.

End your lab

When you have completed your lab, click End Lab. Google Cloud Skills Boost removes the resources you’ve used and cleans the account for you.

You will be given an opportunity to rate the lab experience. Select the applicable number of stars, type a comment, and then click Submit.

The number of stars indicates the following:

  • 1 star = Very dissatisfied
  • 2 stars = Dissatisfied
  • 3 stars = Neutral
  • 4 stars = Satisfied
  • 5 stars = Very satisfied

You can close the dialog box if you don't want to provide feedback.

For feedback, suggestions, or corrections, please use the Support tab.

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

使用无痕浏览模式

  1. 复制系统为实验提供的用户名密码
  2. 在无痕浏览模式下,点击打开控制台

登录控制台

  1. 使用您的实验凭证登录。使用其他凭证可能会导致错误或产生费用。
  2. 接受条款,并跳过恢复资源页面
  3. 除非您已完成此实验或想要重新开始,否则请勿点击结束实验,因为点击后系统会清除您的工作并移除该项目

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。