GithubHelp home page GithubHelp logo

googlecloudplatform / stackdriver-errors-js Goto Github PK

View Code? Open in Web Editor NEW
361.0 29.0 54.0 2.47 MB

Client-side JavaScript exception reporting library for Cloud Error Reporting

Home Page: https://cloud.google.com/error-reporting/

License: Apache License 2.0

JavaScript 97.65% HTML 2.35%
stackdriver javascript crash-reporting error-monitoring client-side

stackdriver-errors-js's Introduction

Experimental Client-side JavaScript library for Cloud Error Reporting

This is not an official Google product. This module is experimental and may not be ready for use.

This experimental library provides Cloud Error Reporting support for client-side web JavaScript applications. Cloud Error Reporting is a feature of Google Cloud Platform that allows in-depth monitoring and viewing of errors reported by applications running in almost any environment. For server-side Node.js error reporting, use cloud-errors-nodejs instead.

Here's an introductory video:

Learn about Cloud Error Reporting

Prerequisites

  1. You need a Google Cloud project.

  2. Enable the Cloud Error Reporting API for your project. We highly recommend to restrict the usage of the key to your website URL only using an 'HTTP referrer' restriction.

  3. Create a browser API key:

    • Follow using api keys instructions to get an API key for your project.
    • Recommended: Use Application restrictions to restrict this key to your website.
    • Recommended: Use API restrictions to limit this key to the Cloud Error Reporting API.

If API keys are not an option for your team, use a custom url to send your errors to your backend.

Quickstart

The library can either be used as a standalone script, or incorporated as a module into a larger javascript application.

For use in any HTML page or without a specific framework, include the standalone script from CDN and set up the error handler in a page load event. For instance, use include the following HTML in the page <head> and replace:

<!-- Warning: Experimental library, do not use in production environments. -->
<script defer src="https://cdn.jsdelivr.net/npm/stackdriver-errors-js@<version>/dist/stackdriver-errors-concat.min.js"></script>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', function() {
  var errorHandler = new StackdriverErrorReporter();
  errorHandler.start({
    key: '<my-api-key>',
    projectId: '<my-project-id>'
    // Other optional arguments can also be supplied, see below.
  });
});
</script>

And that's all you need to do! Unhandled exceptions will now automatically be reported to your project.

Test your setup

Open the page that you instrumented, open the Developer Tools console and enter the following to trigger an unhandled exception:

(function testErrorReporting() {
  window.onerror(null, null, null, null, new Error('Test: Something broke!'));
})();

Open Cloud Error Reporting to view the error and opt-in to notifications on new errors.

Setup for JavaScript

Installing

We recommend using npm: npm install stackdriver-errors-js --save.

Initialization

Create a file that is included in your application entry point and has access to variables myApiKey and myProjectId. For ES6 projects it can be in the form:

// Warning: Experimental library, do not use in production environments.
import StackdriverErrorReporter from 'stackdriver-errors-js';

const errorHandler = new StackdriverErrorReporter();
errorHandler.start({
    key: myApiKey,
    projectId: myProjectId,

    // The following optional arguments can also be provided:

    // service: myServiceName,
    // Name of the service reporting the error, defaults to 'web'.

    // version: myServiceVersion,
    // Version identifier of the service reporting the error.

    // reportUncaughtExceptions: false
    // Set to false to prevent reporting unhandled exceptions, default: `true`.

    // reportUnhandledPromiseRejections: false
    // Set to false to prevent reporting unhandled promise rejections, default: `true`.

    // disabled: true
    // Set to true to not send error reports, this can be used when developing locally, default: `false`.

    // context: {user: 'user1'}
    // You can set the user later using setUser()
});

Note this uses the ES6 import syntax, if your project does not use a compilation step, instead the source with dependencies and polyfills bundled can be used directly:

var StackdriverErrorReporter = require('stackdriver-errors-js/dist/stackdriver-errors-concat.min.js');

var errorHandler = new StackdriverErrorReporter();
errorHandler.start({
    key: myApiKey,
    projectId: myProjectId,
    // Other optional arguments can be supplied, see above.
});

Usage

Unhandled exception will now automatically be sent to Stackdriver Error Reporting.

You can also change your application code to report errors:

try {
  ...
} catch(e) {
  errorHandler.report(e);
}

Or simply:

errorHandler.report('Something broke!');

You can set a user identifier at any time using:

errorHandler.setUser('userId')

Setup for AngularJS

Initialization

  1. Load the dist/stackdriver-errors-concat.min.js JavaScript module.

  2. Implement a new AngularJS exception handler for your application:

angular.module('myAngularApp', [])

  .factory('$exceptionHandler', ['$log', '$window', function($log, $window) {
    var StackdriverErrors = new $window.StackdriverErrorReporter();
    StackdriverErrors.start({
      key: '<my-api-key>',
      projectId: '<my-project-id>',
      // Other optional arguments can be supplied, see above.
    });

    return function(exception, cause) {
      StackdriverErrors.report(exception);
      $log.warn('Reported error:', exception, cause);
    };
  }])

Usage

Uncaught exception in angular expressions will now be reported to Stackdriver Error Reporting.

If you wish, you can manually delegate exceptions, for instance:

try { ... } catch(e) { $exceptionHandler(e); }

Or simply:

$exceptionHandler('Something broke!');

Setup for ReactJS

Follow the general instructions denoted in Setup for JavaScript to load and initialize the library.

There is nothing specific that needs to be done with React, other than making sure to initialize the library in your root entry point (typically index.js).

Source maps

Only publicly available JavaScript source maps are supported.

Your minified file need to be appended with a comment directive to your source map file:

//# sourceMappingURL=http://example.com/path/to/your/sourcemap.map

Configuring without an API key

If you are in a situation where an API key is not an option but you already have an acceptable way to communicate with the Stackdriver API (e.g., a secure back end service running in App Engine), you can configure the endpoint that errors are sent to with the following:

const errorHandler = new StackdriverErrorReporter();
errorHandler.start({
  targetUrl: '<my-custom-url>',
  service: '<my-service>',              // (optional)
  version: '<my-service-version>'       // (optional)
});

where targetUrl is the url you'd like to send errors to and can be relative or absolute. This endpoint will need to support the Report API endpoint.

Custom message dispatching

If you can't use HTTP Post requests for reporting your errors, or in need for some more complicated customizations, you may provide a custom function to handle the reporting.

The function will be called with a payload argument (the same one that would have been sent on the HTTP Post request) and should return a Promise.

const errorHandler = new StackdriverErrorReporter();
function myCustomFunction(payload) {
  console.log("custom reporting function called with payload:", payload);
  return Promise.resolve(); 
}
errorHandler.start({
  customReportingFunction: myCustomFunction,
});

Best Practices

Only reporting in the production environment with Webpack

If using webpack and the DefinePlugin, it is advisable to wrap the initialization logic to only occur in your production environment. Otherwise, with local development you will receive 403s if you restricted your API key to your production environment(which is HIGHLY recommended). The code for this would look something along these lines:

// webpack.production.js

module.exports = {
  // ...
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
  ],
  // ...
}
// index.js

if (process.env.NODE_ENV === 'production') {
  const errorHandler = new StackdriverErrorReporter();
  errorHandler.start({
    key: '<my-project-id>',
    projectId: '<my-project-id>',
  });
}

Usage as a utility

If you would like to use the error logger throughout your application, there are many options that exist. The simplest is to pull the initialization logic into its own file and reference it as necessary throughout your application as a module. An example would be as follows:

// errorHandlerUtility.js
import StackdriverErrorReporter from 'stackdriver-errors-js';

let errorHandler;

if (process.env.NODE_ENV === 'production') {
  errorHandler = new StackdriverErrorReporter();
  errorHandler.start({
    key: '<my-project-id>',
    projectId: '<my-project-id>',
    // Other optional arguments can be supplied, see above.
  });
} else {
  errorHandler = {report: console.error};
}

export default errorHandler;

Consumption of errorHandlerUtility would essentially follow the following pattern:

import errorHandler from './errorHandlerUtility';

try {
  someFunctionThatThrows();
} catch (error) {
  errorHandler.report(error);
}

If the call to report has additional levels of wrapping code, extra frames can be trimmed from the top of generated stacks by using a number greater than one for the skipLocalFrames option:

import errorHandler from './errorHandlerUtility';

function backendReport (string) {
  // Skipping the two frames, for report() and for backendReport()
  errorHandler.report(error, {skipLocalFrames: 2});
}

FAQ

Q: Should I use this code in my production application? A: This is an experimental library provided without any guarantee or official support. We do not recommend using it on production without performing a review of its code.

Q: Are private source maps supported? A: No, see issue #4.

Q: Can I propose changes to the library? A: Yes, see the Contributing documentation for more details.

stackdriver-errors-js's People

Contributors

0xsage avatar arnaudvalle avatar bjon avatar bz2 avatar davidespinola avatar dependabot[bot] avatar jastrzebowski avatar jmasukawa avatar k0walik avatar kospl avatar mikelambert avatar minishlink avatar oshalygin avatar steren avatar theorchoo avatar tinovyatkin avatar toebbel avatar trevtrich avatar xlfe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stackdriver-errors-js's Issues

Fails to report an Angular `HttpErrorResponse`

As is

  • Using Angular
  • Make a service request, throw a 500HttpErrorResponse
  • Report this error with StackdriverErrorHandler
  • Get a 400 from the service, error never reported

These errors do not have a stack trace, so the payload sent to the clouderrorreporting api was:

{
  "serviceContext": { "service": "my-service" },
  "context": {
    "httpRequest": {
      "userAgent": "Mozilla/5.0 ...",
      "url": "http://localhost:3000/app/123"
    }
  },
  "message": "Error extracting stack trace: Error: Cannot parse given Error object\n[object Object]\n    (::)"
}

The service then responded with:

400 - ReportedErrorEvent.context must contain a location unless message contain an exception or stacktrace.

Expected

Errors without a stack would be serialized in a way to maintain as much information as possible.

It is surprising to send "Error extracting stack trace" instead of a message representing the error trying to be reported.

One quick fix I tried to implement was to JSON.stringify errors before reporting, those were rejected by the service as "too long".

Overall, would love if the client would do everything possible to ensure the error gets reported.

Proposed API and build improvements

Thanks for publishing this library, have been using it a quite heavily over the last few months to record frontend errors in the same place as we track backend problems. Out of this, I'd like to submit some improvements, some of which may require some discussion and decisions, so this is a meta issue for tracking the proposed changes.

Library API

Currently StackdriverErrorReporter exposes a callback parameter in a few places, mostly to enable the testing. This allows some errors to be seen by callers, but does not expose the extracted stacktrace message and is somewhat awkward to use. As stacktrace-js already uses promises, I suggest the interface here should too. The promise api is widely available and there's a polyfill bundled in the build already (though this may want some tweaking, see below).

  • Return a Promise from report() and sendErrorPayload() #50
  • Propagate payload (or just payload.message) when promise is fulfilled #59
  • Add config option to output message to console.log #6
  • Handle non-200 HTTP responses #32

When calling report() directly from a logging framework, stacktraces for strings currently start inside the logger rather than at the caller.

  • Expose firstFrameIndex as an argument to report() #58

Build and packaging

This is a simple library and doesn't need a complicated build, but there are a few niggles currently when embedding in a modern webapp, and the single file bundle could also been improved. Not sure how far to go on this front, but there are some simple improvements to make at least.

  • Update devDependencies to latest versions #49
  • Remove 'dist' folder from version control #48
  • Make npm start launch the demo in a browser window #52
  • Enable ES6 import without hack #2

Reduce the bundle size

Currently requiring stackdriver-errors-js results in quite a lot of code being pulled in -- it's one of our largest dependencies.

Screenshot 2021-02-26 at 18 55 52

The above is generated using https://github.com/webpack-contrib/webpack-bundle-analyzer.

Stat Size: 136.64KB (before minification)
Parsed Size: 39.06 KB (after minification)
Gzipped: 11.65KB (after minification + gzip)

Although it's not strictly because of code in stackdriver-errors-js, I figured this is a good place to start to get an understanding of what really is required to report errors to stackdriver.

In particular I'd love to find out how important stacktrace-js is to this libraries functionality and whether there are opportunities to cut it or use an alternative dependency -- I wonder if it's supporting very old browsers / edge cases which are no longer relevant to everybody ๐Ÿค”

I'm tempted to just try to write a simple stackdriver API wrapper without stacktrace-js but of course there's every chance I'll end up going through the exact same process this library went through and realise it's not possible without those large dependencies so any advice is welcome!

Error string normalization

I'm not sure if this is within the scope of this project or not. But I did notice that different browsers will have different error strings for the same error. E.g.

ReferenceError: Can't find variable: errorHandler
in
Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.79 Mobile/14A456 Safari/602.1

vs

ReferenceError: errorHandler is not defined
in
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.70 Safari/537.36

The full stack trace isn't the exact same either, just function names differ I think:

ReferenceError: errorHandler is not defined
at <anonymous> (https://redditp.com/js/script.js:615)
at Object.success (https://redditp.com/js/EmbedIt.js:94)
at i (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:2)
at Object.fireWith (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:2)
at z (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:4)
at HTMLScriptElement.c (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:4)
at HTMLScriptElement.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:3)
at HTMLScriptElement.r.handle (jquery.min.js:3)

vs

ReferenceError: Can't find variable: errorHandler
at <anonymous> (https://redditp.com/js/script.js:615)
at success (https://redditp.com/js/EmbedIt.js:94)
at i (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:2)
at fireWith (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:2)
at z (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:4)
at c (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:4)
at dispatch (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:3)
at handle (https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js:3)

Cannot set property onunhandledrejection of [object Object] which has only a getter

This may have birthed from Issue#35.

I'm seeing logs with the following error:

TypeError: Cannot set property onunhandledrejection of [object Object] which has only a getter
    at onunhandledrejection (../node_modules/stackdriver-errors-js/stackdriver-errors.js:91:0)
    at window.addEventListener (index.js:133:15)

This is happening on my starting the ErrorReporter. index.js:133 is line 3:

window.addEventListener('DOMContentLoaded', function () {
  var errorHandler = new StackdriverErrorReporter();
  errorHandler.start({
    targetUrl: '<my_url>',
  });
})

User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36

Count sessions on Stack Driver Error Reporting?

It would be nice if there was a way to see "percentage of sessions with errors" on the error reporting dashboard. Having 20 errors per day is horrible if you had 20 sessions, but it's nothing to worry about if you had 200,000 sessions.

Support private source maps

The library only supports source maps when:

  • The minified file is appended with a comment directive to your source map file:

    //# sourceMappingURL=http://example.com/path/to/your/sourcemap.map
  • And this file is publicly accessible.

Including server-side component, we could imagine a way to not need to make the source map available publicly.

Cross origin error while send

I've got this error in browser when try to use report method:

Access to XMLHttpRequest at 'webpack:///node_modules/stackdriver-errors-js/stackdriver-errors.js' from origin 'https://mysite.com' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

I init error reporter using such code:

  window.StackTrace = require('stacktrace-js')
  window.StackTrace.get({ offline: true })
  const { StackdriverErrorReporter } = require('stackdriver-errors-js')

  window.addEventListener('DOMContentLoaded', function () {
    window.errorHandler = new StackdriverErrorReporter()
    window.errorHandler.start({
      key: apiKey,
      projectId: 'my-projectid',
      reportUncaughtExceptions: isProduction,
      service: 'serviceName',
      version: buildNo
    })    
    if (process.env.NODE_ENV === 'development') {
      window.errorHandler.setUser('dev')
    }
  })

Problem doing manual error reporting

Hi, I have code that does:

// In a promise `then` handler:
myRegister(new Error('some error'));
// ...
// Elsewhere in the code:
errorHandler.report(theNewError);

but the stackdriver API response is:

{
  "error": {
    "code": 400,
    "message": "ReportedErrorEvent.context must contain a location unless `message` contain an exception or stacktrace.",
    "status": "INVALID_ARGUMENT"
  }
}

The request that is sent to stackdriver is:

{
  "serviceContext": {"service": "webApp", "version": "whatever"},
  "context": {
    "user": "Joe User",
    "httpRequest": {
      "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
      "url": "http://localhost:3000/"
    }
  },
  "message": "Error: {\"type\":\"An error during API handling\"}\n    at then(function (/Users/murphyke/Documents/code/myapp/web/src/actions.js:224:0)"
}; 

What is the recommendation? Do I have to annotate the error object somehow?

Unhandled exceptions are reported correctly.

Using Chrome, btw.

Send additional context info

Not sure how should I solve if I wan't to send with error additinal info about user context, for example, current browser window size?

I thought it could be added to context obj, but it seems it doesn't work this way. And context.user is just a string, should I stringify all the context info into this prop?

How this case should be handled? I think this problem should be mentioned in docs.

Add playground

Add an demo page where users and developers can provide an API key and project ID and test the library.

Any solution for Angular 2+

Hello,

Is there a version available for Angular 2+? I need to write logs from my Angular 5 app.

Thank you

Error message not sent when reporting from Chrome's console.

The example string error report: errorHandler.report('Something broke!'); causes this:

{
  "error": {
    "code": 400,
    "message": "ReportedErrorEvent.context must contain a location unless `message` contain an exception or stacktrace.",
    "status": "INVALID_ARGUMENT"
  }
}

CDNs

Rawgit is fine for examples but imo for a production setup would be nice to have a CDN published version. Should we use Google, or an external one like cdnjs.com?

Do not override window.onerror

If window.onerror is already defined, stackdriver-errors should not override it but instead add the its error handler on top of it.

Preventing StackTrace is not defined on browser when using Browserify

I'm trying to use this lib with Browserify + ES6 syntax.

import { StackdriverErrorReporter } from 'stackdriver-errors-js'

But, when I try to test it with some error I receive this:

Uncaught ReferenceError: StackTrace is not defined at StackdriverErrorReporter.report

image

Error line

Everything works fine when I use self-hosted CDN.

Infinite loop when API quota is exceeded and reportUncaughtExceptions is enabled

When there are large volumes of errors that exceed Stackdriver reporting quota, HTTP 429 responses are received as a response, letting the caller know too many requests are being sent.

These are thrown as errors by StackdriverErrorReporter here:
https://github.com/GoogleCloudPlatform/stackdriver-errors-js/blob/master/stackdriver-errors.js#L184

If reportUncaughtExceptions is enabled, then this results in the reporter trying to report those errors, receiving more HTTP 429 responses, and going into an infinite loop.

The end result is a tab "crash" (infinite loop causing CPU to be used at 100% and browser tab to become unresponsive).

I can do the work to create a fix and send over a PR, but I'm a little unsure of the best way to handle this scenario.

  1. We could just not log these, but it might be useful to surface this somehow so you'd be aware you're exceeding your quota?

  2. One thought is to sample those kinds of errors at a reduced rate, i.e.

if (xhr.status === 429 && Math.random() > 0.99) {
  // throw the error
}

I mean, you wouldn't get a lot of them, but it might be enough that you'd investigate the issue?

Appreciate any thoughts / feedback on how to fix this, thanks!

Reporting unhandled promise rejections

It looks like support for an event similar to onerror but meant for unhandled promise rejections called onunhandledrejection (spec here) is on it's way, but is not supported very broadly thus far (mdn here).

Is there any discussion going on to support this? Would the maintainers be open to a PR for this? I'm thinking it'd belong in this block.

Send logs that aren't errors

Can this turn into a more 'general' logging solution for websites to send logs from the client?
I would like to have the ability to send metric based logs from my web app, and also log messages that aren't specifically errors.
(I will write the functionality myself if there's a chance it will be accepted)

Provide JS module

Installing via a script is not the preferred way to install dependencies in a modern web application.

Developers should be able to use the library by importing a module in their application.

We should be compatible with the common module conventions (AMD, CommonJS, JS modules?)

Error when generating new `dist` version

I tried generating a new version with npm run dist, but I got:

$ npm run dist

> [email protected] dist /workspaces/stackdriver-errors-js
> gulp lib-concat

fs.js:45
} = primordials;
    ^

ReferenceError: primordials is not defined
    at fs.js:45:5
    at req_ (/workspaces/stackdriver-errors-js/node_modules/natives/index.js:143:24)
    at Object.req [as require] (/workspaces/stackdriver-errors-js/node_modules/natives/index.js:55:10)
    at Object.<anonymous> (/workspaces/stackdriver-errors-js/node_modules/vinyl-fs/node_modules/graceful-fs/fs.js:1:37)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dist: `gulp lib-concat`
npm ERR! Exit status 1

What happens when I create 2 reporter instances?

Quick question: If I initiate two reporter instances, will uncaught errors be sent twice?

Here's my setup (may not be important info for answering the question, but just in case): My app has a main window and an embedded iframe which is another site. I installed this package in the main window. I can't install it in the iframe site, but I can use postMessage to pass caught errors to the main site, then reported them. I want to initiate 2 separate instances in order to have different service name and version numbers, but I wonder what will happen to uncaught errors in the main window.

report() should allow handling of non-200 Stackdriver responses

Current API signature:

report(e, callback), where callback happens on both success or failure (passed XHR error on transaction failure).

In the event that the Stackdriver XHR succeeds with a non-200, e.g. 403 due to API key origin restriction, callback is invoked without parameters, so it looks like a success to the client. This is because XMLHttpRequest.onerror is not dependent on the HTTP status code: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror

Relevant code:

xhr.onerror = function(e) {

Possibly this method could be changed to accept two callbacks, or else use a Promise. The error path should trigger if the HTTP response status is not a 200.

Filter errors

We get a lot of noise from code we don't care so much about such as random chrome extensions or occasionally bad third party scripts which we can't do anything about.

ReferenceError: GLOBALS is not defined at Gmail (chrome-extension://edmfnamdkbpibmfhghablbnabapbaflf/gmail.js:13:27) at (:1:13)

I wondered if it'd be possible to only log errors which originate from first party scripts; I guess supporting an option which allows errors to be filtered out might worth for this?

AppEngine Standard - Report API

Hello there,

As other issues have mentioned, there are some security considerations with regards to hitting the stackdriver API with an API Key. I opted to implement a backend service to forward messages along to the Report API.

AppEngine standard is configured to automatically send log messages to stackdriver, which is super convenient. Unfortunately it's fairly limited to using the logging API. It works, but records get merged with all the other server side logs, the function name ends up being the endpoint, and httpContext doesn't get captured.

I tried lots of shenanigans with building my own LogRecord object and sending it to the logger, but to no avail.

I could setup API keys and use the google.cloud libbrary to hit the Report API directly, but that defeats the purpose/benefit of using AppEngine standard!

Is there advice on a better API/route to create StackDriver logs from AppEngine standard?

---- EDIT ---
So far this is the best solution I have for an AppEngine Standard + Python 2.7 + Flask blueprint.

I pull out the URL from the context and stuff it into the message.

from flask import Blueprint, request
import logging

ERR = Blueprint('Stackdriver', __name__)


@ERR.route('/client_error', methods=['POST'])
def client_error():
    json = request.get_json()
    msg = "Page: {page}\n{message}".format(
        page=json['context']['httpRequest']['url'], message=json['message'])

    logging.error(msg)

    return ""

Integration with ReactJs?

Anyone have a how-to or can direct me on how to get going with this? Outside of adding the scripts to the bottom of the the root index file?

Going to give this a whirl over the next few days but would love to see any insight.

Fails in Chrome 57 due to sendBeacon()

It looks like sendBeacon() cannot be used with the ContentType "application/json; charset=UTF-8"

According to https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain

More info at http://crbug.com/490015

Full error:

Uncaught (in promise) DOMException: Failed to execute 'sendBeacon' on 'Navigator': sendBeacon() with a Blob whose type is not CORS-safelisted MIME type is disallowed experimentally. See http://crbug.com/490015 for details.
    at n.sendErrorPayload (https://cdn.rawgit.com/GoogleCloudPlatform/stackdriver-errors-js/v0.0.5/dist/stackdriver-errors-concat.min.js:2:16470)
    at https://cdn.rawgit.com/GoogleCloudPlatform/stackdriver-errors-js/v0.0.5/dist/stackdriver-errors-concat.min.js:2:16135

Out of "experimental"?

Are there any plans for this to be out of experimental mode and considered production ready?

Can I call `errorHandler.setUser()` before `errorHandler.start()`?

const errorHandler = new StackdriverErrorReporter();
errorHandler.setUser('some_user_id');
errorHandler.start({ ...config, service: 'some_service_name' });

README says setUser can be called "at any time", but I just want to confirm, can I call it before start()?

In my code, I call setUser() when user id becomes available, and call start() when service name becomes available, and I can't guarantee their order.

Thanks!

StackTrace is not defined

image

I tried to quickly connect and test and got this error. I'm using webpack/react and used it like this.

var StackdriverErrorReporter = require("stackdriver-errors-js").StackdriverErrorReporter;

export function initErrorLogging() {
  const errorHandler = new StackdriverErrorReporter();
  errorHandler.start({
    key: STACKDRIVER_API_KEY,
    projectId: GCP_PROJECT_ID,
    //service: '<my-service>',              // (optional)
    //version: '<my-service-version>'       // (optional)
  });
}

I suppose you could include StackTrace as a dependency.

Publish to npm

Bower does not seem to be a thing anymore. But developers expect to install client-side dependencies via npm.

We should provide an npm module.

Suggested pattern for sending to server that proxies on to Stackdriver

Our policies won't allow us to have an api key directly in our calls given that we can't lock down an api key to only the Stackdriver Errors API. Do you have any recommendation for shaping these errors so that we can "proxy" them through our app engine server? You've done a fair bit of work in getting this shape right prior to shipping it up to the api directly, so I'd like to leverage that, but I'm not seeing a great way of doing that without just pulling out the code into my own module.

Where do you see user in error reporting?

If I set the user context , is there a way to see this in the Google Error Reporting console?? I've defined it, but I don't see a way to add/show this data in the console itself.

 errorHandler.start({
 ....
    context: {user: 'User1'}
  });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.