Hello World error

Demonstrates how to report an error.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample

C++

#include <google/cloud/functions/http_request.h>
#include <google/cloud/functions/http_response.h>
#include <nlohmann/json.hpp>
#include <iostream>

namespace gcf = ::google::cloud::functions;

// Though not used in this example, the request is passed by value to support
// applications that move-out its data.
gcf::HttpResponse hello_world_error(gcf::HttpRequest request) {  // NOLINT
  if (request.target() == "/return500") {
    // An error response code does NOT create entries in Error Reporting
    return gcf::HttpResponse{}.set_result(
        gcf::HttpResponse::kInternalServerError);
  }
  // Unstructured logs to stdout and/or stderr do NOT create entries in Error
  // Reporting
  std::cout << "An error occurred (stdout)\n";
  std::cerr << "An error occurred (stderr)\n";

  if (request.target() == "/throw/exception") {
    // Throwing an exception WILL create new entries in Error Reporting
    throw std::runtime_error("I failed you");
  }

  // Structured logs MAY create entries in Error Reporting depending on their
  // severity. You can create structured logs manually (as shown here), or using
  // your favorite logging library with suitable formatting.
  std::cerr << nlohmann::json{{"severity", "info"},
                              {"message", "informational message"}}
                   .dump()
            << std::endl;

  std::cerr << nlohmann::json{{"severity", "error"},
                              {"message", "an error message"}}
                   .dump()
            << std::endl;

  return gcf::HttpResponse{}
      .set_header("content-type", "text/plain")
      .set_payload("Hello World!");
}

Go


package tips

import (
	"fmt"
	"net/http"
	"os"
)

// HTTPError describes how errors are handled in an HTTP function.
func HTTPError(w http.ResponseWriter, r *http.Request) {
	// An error response code is NOT reported to Error Reporting.
	// http.Error(w, "An error occurred", http.StatusInternalServerError)

	// Printing to stdout and stderr is NOT reported to Error Reporting.
	fmt.Println("An error occurred (stdout)")
	fmt.Fprintln(os.Stderr, "An error occurred (stderr)")

	// Calling log.Fatal sets a non-zero exit code and is NOT reported to Error
	// Reporting.
	// log.Fatal("An error occurred (log.Fatal)")

	// Panics are reported to Error Reporting.
	panic("An error occurred (panic)")
}

Java


import com.google.cloud.functions.HttpFunction;
import com.google.cloud.functions.HttpRequest;
import com.google.cloud.functions.HttpResponse;
import java.io.IOException;
import java.util.logging.Logger;

public class HelloError implements HttpFunction {

  private static final Logger logger = Logger.getLogger(HelloError.class.getName());

  @Override
  public void service(HttpRequest request, HttpResponse response)
      throws IOException {
    // These will NOT be reported to Stackdriver error reporting
    System.err.println("I failed you");
    logger.severe("I failed you");

    // This WILL be reported to Stackdriver error reporting
    throw new RuntimeException("I failed you");
  }
}

Node.js

// These WILL be reported to Stackdriver Error Reporting
console.error(new Error('I failed you'));
console.error('I failed you', new Error('I failed you too'));
throw new Error('I failed you'); // Will cause a cold start if not caught

// These will NOT be reported to Stackdriver Error Reporting
console.info(new Error('I failed you')); // Logging an Error object at the info level
console.error('I failed you'); // Logging something other than an Error object
throw 1; // Throwing something other than an Error object
callback('I failed you');
res.status(500).send('I failed you');

Python

# This WILL be reported to Stackdriver Error
# Reporting, and WILL NOT show up in logs or
# terminate the function.
from google.cloud import error_reporting
client = error_reporting.Client()

try:
    raise RuntimeError('I failed you')
except RuntimeError:
    client.report_exception()

# This WILL be reported to Stackdriver Error Reporting,
# and WILL terminate the function
raise RuntimeError('I failed you')

# These errors WILL NOT be reported to Stackdriver
# Error Reporting, but will show up in logs.
import logging
print(RuntimeError('I failed you (print to stdout)'))
logging.warn(RuntimeError('I failed you (logging.warn)'))
logging.error(RuntimeError('I failed you (logging.error)'))
sys.stderr.write('I failed you (sys.stderr.write)\n')

# This is considered a successful execution and WILL NOT be reported to
# Stackdriver Error Reporting, but the status code (500) WILL be logged.
from flask import abort
return abort(500)

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.