Giter VIP home page Giter VIP logo

errorhandler's Introduction

This is a library for Google Apps Script projects. It provides methods to perform an Exponential backoff logic whenever it is needed and rewrite error objects before sending them to Stackdriver Logging.

Methods

expBackoff(func, options)

In some cases, Google APIs can return errors on which it make sense to retry, like 'We're sorry, a server error occurred. Please wait a bit and try again.'.

In such cases, it make sense to wrap the call to the API in an Exponential backoff logic to retry multiple times.

Note that most Google Apps Script services, like GmailApp and SpreadsheetApp already have an Exponential backoff logic implemented by Google. Thus it does not make sense to wrap every call to those services in an Exponential backoff logic.

Things are different for Google Apps Script advanced services where such logic is not implemented. Thus this method is mostly useful for calls linked to Google Apps Script advanced services.

Example

// Calls an anonymous function that gets the subject of the vacation responder in Gmail for the currently authenticated user.

 var responseSubject = ErrorHandler.expBackoff(function(){return Gmail.Users.Settings.getVacation("me").responseSubject;});

Parameters

Name Type Default value Description
func Function The anonymous or named function to call.
options Object {} OPTIONAL, options for exponential backoff
options.throwOnFailure boolean false If true, throw a CustomError on failure
options.doNotLogKnownErrors boolean false If true, will not log known errors to stackdriver
options.verbose boolean false If true, will log a warning on a successful call that failed at least once
options.retryNumber number 5 Maximum number of retry on error

Return

The value returned by the called function, or a CustomError on failure if options.throwOnFailure == false

CustomError is an instance of Error

urlFetchWithExpBackOff(url, params)

This method works exactly like the fetch() method of Apps Script UrlFetchApp service.

It simply wraps the fetch() call in an Exponential backoff logic.

We advise to replace all existing calls to UrlFetchApp.fetch() by this new method.

UrlFetchApp.fetch(url, params) => ErrorHandler.urlFetchWithExpBackOff(url, params)

logError(error, additionalParams)

When exception logging is enabled, unhandled exceptions are automatically sent to Stackdriver Logging with a stack trace (see official documentation).

But if you wrap your code in a try...catch statement and use console.error(error) to send the exception to Stackdriver Logging, only the error message will be logged and not the stack trace. This method will also leverage the list of known errors and their translation to better aggregate on Stackdriver Logging: the message will be the English version if available.

We advise to replace all existing calls to console.error(error) by this new method to correctly log the stack trace, in the exact same format used for unhandled exceptions.

console.error(error) => ErrorHandler.logError(error)

Parameters

Name Type Default value Description
error String, Error, or { lineNumber: number, fileName: string, responseCode: string} A standard error object retrieved in a try...catch statement or created with new Error() or a simple error message or an object
additionalParams Object, {addonName: string} {} Add custom values to the logged Error, the 'addonName' property will pass the AddonName to remove from error fileName
options Object {} Options for logError
options.asWarning boolean false If true, use console.warn instead console.error
options.doNotLogKnownErrors booleab false if true, will not log known errors to stackdriver

Return

Return the CustomError, which is an Error, with a property 'context', as defined below:

/**
 * @typedef {Error} CustomError
 *
 * @property {{
 *   locale: string,
 *   originalMessage: string,
 *   knownError: boolean,
 *   variables: Array<{}>,
 *   errorName: string,
 *   reportLocation: {
 *     lineNumber: number,
 *     filePath: string,
 *     directLink: string,
 *   },
 * }} context
 */

getNormalizedError(localizedErrorMessage, partialMatches)

Try to get the corresponding english version of the error if listed in this library.

There are Error match exactly, and Errors that can be partially matched, for example when it contains a variable part (eg: a document ID, and email)

To get variable part, use the following pattern:

var variables = []; // The empty array will be filled if necessary in the function
var normalizedError = ErrorHandler.getNormalizedError('Documento 1234567890azerty mancante (forse è stato eliminato?)', variables);

// The normalized Error, with its message in English, or '' of no match are found:
// normalizedError = 'Document is missing (perhaps it was deleted?)'

// the variable part:
// variables = [{variable: 'docId', value: '1234567890azerty'}]

Parameters

Name Type Default value Description
localizedErrorMessage String The Error message in the user's locale
partialMatches Array<{ variable: string, value: string }> [] OPTIONAL, Pass an empty array, getNormalizedError() will populate it with found extracted variables in case of a partial match

The value returned is the error in English or '' if no matching error was found

getErrorLocale(localizedErrorMessage)

Try to find the locale of the localized thrown error

Parameters

Name Type Default value Description
localizedErrorMessage String The Error message in the user's locale

Return

The locale ('en', 'it', ...) or '' if no matching error found

NORMALIZED_ERRORS

constant

List all known Errors in a fixed explicit English message. Serves as reference for locallizing Errors.

Use this to check which error a normalized error is:

var normalizedError = ErrorHandler.getNormalizedError('Documento 1234567890azerty mancante (forse è stato eliminato?)');

if (normalizedError === ErrorHandler.NORMALIZED_ERRORS.DOCUMENT_MISSING) {
  // Do something on document missing error
}

NORETRY_ERRORS

constant

List all Errors for which there are no benefit in re-trying

Setup

You can copy the code of this library in your own Google Apps Script project or reuse it as a standard library. In both cases, methods are called using the ErrorHandler class / namespace, meaning you will use them exactly in the same way.

To install it as a library, use the following script ID and select the latest version:

1mpYgNprGHnJW0BSPclqNIIErVaTyXQ7AjdmLaaE5O9s9bAOrsY14PMCy

To copy the code in your project, simply copy-past the content of this file in a new script file in your project:

https://github.com/RomainVialard/ErrorHandler/blob/master/src/ErrorHandler.gs.js

NPM install:

To be documented

Warning

This library contains 5 methods directly available as functions and callable without using the ErrorHandler class / namespace:

  • expBackoff()
  • urlFetchWithExpBackOff()
  • logError()
  • getNormalizedError()
  • getErrorLocale()

and 2 Object constant

  • NORMALIZED_ERRORS
  • NORETRY_ERRORS

For this reason, if you copy the code in your project, make sure you don't have any other function with the exact same name.

errorhandler's People

Contributors

jeanremidelteil avatar romainvialard avatar

Stargazers

 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

errorhandler's Issues

How to contribute/ask about error messages?

I found a conversation where Romain and Jean-Remi mentioned this repo while I was researching about an add-on error message, more explicitely about "You do not have permission to call showSidebar at functionName (fileName: lineNumber)". This error occurs on add-ons triggers created by user A from mydomain.com that are activated by actions made by user B from domain otherdomain.com when functionName tries to open a sidebar.

  1. Are this kind of errors something of interest for you?
  2. I didn't tried yet this library but if this error message isn't catched could I ask about it here?

Something like the following should help to reproduce the error message.

function onInstall(event) {
  onOpen(event);
}

function onOpen(event){
  SpreadsheetApp
  .getUi()
  .createAddonMenu()
  .addItem('Add trigger', 'addTrigger')
  .addItem('Remove all triggers', 'removeTriggers')
  .addToUi();
}

function addTrigger(){
  ScriptApp.newTrigger('respondeToSpreadsheetEdit')
  .forSpreadsheet(SpreadsheetApp.getActive())
  .onEdit()
  .create();
  SpreadsheetApp.getUi().alert('Trigger added.');
}

function respondeToSpreadsheetEdit(event){
  var html = '<p>Hello world!</p>';
  var title = 'Sidebar title';
  var userInterface = HtmlService.createHtmlOutput(html)
  .setTitle(title);
  SpreadsheetApp.getUi().showSidebar(userInterface);
}

function removeTriggers(){
  var triggers = ScriptApp.getProjectTriggers();
  triggers.forEach(function(trigger){
    ScriptApp.deleteTrigger(trigger);
  });
  SpreadsheetApp.getUi().alert('All triggers were removed.');

}

Steps to reproduce the error message

  1. Publish the above code as a Google Sheets add-on
  2. User A install the add-on, click on Add-ons > Add-on name > Add trigger
  3. User A shares the spreadsheet with user B
  4. User B edit cell A1
  5. Open the Stackdriver log for the add-on. There you will find something like the following:

You do not have permission to call showSidebar at respondToSpreadsheetEdit(Code:n)

where n is the code line number for SpreadsheetApp.getUi().showSidebar(userInterface);

P.S. Spanish version of the error message

No cuenta con el permiso para llamar a showSidebar at respondeToSpreadsheetEdit(Código:27)


Related issue on the Apps Script Issue Tracker

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.