1.2.0 • Published 7 months ago

@beforeyoubid/error-adapter v1.2.0

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

BYB Error Adapter

This is an error handling module that supports multiple error types and the handling of each type accordingly using Sentry.

The following npm packages have been extended in this module:

  • Sentry's @sentry/node library, which does not support the filtration of local errors by default, and the use of an environment variable to disable Sentry alerts.
  • The serverless-sentry-lib library, which does not support the use of an environment flag to disable Sentry alerts.

This module supports using environment variables to filter local error alerts, as well as disabling error alerts entirely. This is especially useful for microservice architectures where errors may be handled elsewhere.

Supported Error types

Error TypeAlert Raised in Sentry
Server ErrorYes
Not AuthorizedYes
Not AuthenticatedNo
Not FoundNo
Validation ErrorNo
Payment ErrorNo
User Input ErrorNo
Conflict ErrorNo
External API ErrorNo
System ErrorNo

This module is designed to work on a native node runtime and in a Lambda environment. For Lambda, please see the withSentry section below.

Setup

Installation

  yarn add @beforeyoubid/error-adapter

Environment Variables

Capturing can be controlled through the following environment variables. You can set them manually in your serverless.yml (Serverless Framework) or template.yml (AWS SAM) or let them be configured automatically using the Serverless Sentry Plugin during deployment.

Environment VariableDescription
SENTRY_DSNSentry DSN Url
SENTRY_ENVIRONMENTEnvironment (optional, e.g. "dev" or "prod")
SENTRY_RELEASERelease number or version of your project (optional)
SENTRY_AUTO_BREADCRUMBSAutomatically create breadcrumbs (see Sentry SDK docs, default to true)
SENTRY_FILTER_LOCALDon't report errors from local environments (defaults to true)
SENTRY_CAPTURE_ERRORSEnable capturing Lambda errors (defaults to true)
SENTRY_CAPTURE_UNHANDLEDEnable capturing unhandled Promise rejections (defaults to true)
SENTRY_CAPTURE_UNCAUGHTEnable capturing uncaught exceptions (defaults to true)
SENTRY_CAPTURE_MEMORYEnable monitoring memory usage (defaults to true)
SENTRY_CAPTURE_TIMEOUTSEnable monitoring execution timeouts (defaults to true)
SENTRY_SOURCEMAPSEnable Webpack sourcemaps support (defaults to false)
DISABLE_SENTRYDisable Sentry, not set automatically (defaults to false)

Use Together With the Serverless Sentry Plugin

The Serverless Sentry Plugin allows simpler configuration of the library through the serverless.yml and will upload your source-maps automatically during deployment. This is the recommended way of using the serverless-sentry-lib library.

Instead of manually setting environment variables, the plugin determines and sets them automatically. In the serverless.yml simply load the plugin and set the dsn configuration option as follows:

service: my-serverless-project
provider:
  # ...
plugins: serverless-sentry
custom:
  sentry:
    dsn: https://xxxx:yyyy@sentry.io/zzzz # URL provided by Sentry
    filterLocal: true # Optional

You can still manually set environment variables on a per-function level to overwrite the default ones. Please refer to the Serverless Sentry Plugin for full documentation of all available options.

Usages

The module caters for the following usage mechanisms:

  • Using withSentry higher-order function.
    • This can be used in confuction with the formatErrors function (see below).
    • Used to wrap a Lambda handler to capture exceptions as per the serverless-sentry-lib library.
  • Using formatErrors function to format and capture errors caught by GraphQL.
    • This can be passed into a GraphQL handler function to format and send errors to Sentry.
  • Using handleErrorSentryOptions to apply the above rules to your own Sentry client.
  • Adding custom Sentry options in conjunction with the options provided by this library.

1) Using withSentry higher-order function

Original Lambda Handler Code:

  export async function handler(event, context) {
    console.log("EVENT: \n" + JSON.stringify(event, null, 2));
    return context.logStreamName;
  }

New Lambda Handler Code Using withSentry For Sentry Reporting

  import { withSentry } from "@beforeyoubid/error-adapter"; // This helper library

  export const handler = withSentry(async (event, context) => {
    console.log("EVENT: \n" + JSON.stringify(event, null, 2));
    return context.logStreamName;
  });

Custom configuration options may also be used. Please refer to the Serverless Sentry Plugin for full documentation of all available options.

2) Using formatErrors function to handle errors caught by GraphQL

import { ApolloServer } from 'apollo-server-lambda';
import schema from '../graphql';
import { formatError, withSentry } from '@beforeyoubid/error-adapter';

const server = new ApolloServer({
  schema,
  formatError,
  context: async ({ event, context }): Promise<ApplicationContext> => {
    const headers = {};
    let gqcontext = {};
    if (event.headers) {
      const sourceUserAgent =
        _.get(event, 'headers.x-source-user-agent') || _.get(event, 'headers.X-Source-User-Agent');

      gqcontext = {
        sourceUserAgent,
      };
    }
    return {
      // cache,
      functionName: context.functionName,
      headers,
      ...gqcontext,
    };
  },
});

const graphqlHandler = server.createHandler({
  cors: {
    origin: '*',
    methods: ['POST'],
  },
});

export default withSentry(graphqlHandler);

3) Using handleErrorSentryOptions to apply the above rules to your own Sentry client.

With GraphQL

Using handleErrorSentryOptions function to send errors to Sentry by passing handleErrorSentryOptions function into Lambda GraphQL handler.

import { ApolloServer } from 'apollo-server-lambda';
import withSentry from 'serverless-sentry-lib';
import schema from '../graphql';
import { formatError, handleErrorSentryOptions } from '@beforeyoubid/error-adapter';

const server = new ApolloServer({
  schema,
  formatError,
  context: async ({ event, context }): Promise<ApplicationContext> => {
    const headers = {};
    let gqcontext = {};
    if (event.headers) {
      const sourceUserAgent =
        _.get(event, 'headers.x-source-user-agent') || _.get(event, 'headers.X-Source-User-Agent');

      gqcontext = {
        sourceUserAgent,
      };
    }
    return {
      // cache,
      functionName: context.functionName,
      headers,
      ...gqcontext,
    };
  },
});

const graphqlHandler = server.createHandler({
  cors: {
    origin: '*',
    methods: ['POST'],
  },
});

export default withSentry(handleErrorSentryOptions, graphqlHandler);

Using without GraphQL

import withSentry from 'serverless-sentry-lib';
import { handleErrorSentryOptions NotFound } from '@beforeyoubid/error-adapter';

export const cronHandler = withSentry(handleErrorSentryOptions, async (event, context) => {
  console.log('EVENT: \n' + JSON.stringify(event, null, 2));
  throw new Error('This error will be raised in Sentry');
  return context.logStreamName;
});

3) Adding custom Sentry options in conjunction with the options provided by this library.

This is particularly useful when the Sentry client must be initialized as early as possbile. eg. when using Sentry with express. The library will apply the options highlighted above with the options passed into the Sentry.initialise() function.

import express from 'express';
import { Sentry, withSentry } from '@beforeyoubid/error-adapter';
import * as Tracing from '@sentry/tracing';

const app = express();
Sentry.initialise({
  integrations: [
    // enable HTTP calls tracing
    new Sentry.Integrations.Http({ tracing: true }),
    // enable Express.js middleware tracing
    new Tracing.Integrations.Express({ app }),
  ],

  // amount of performance reports (out of 1) are sent to sentry
  tracesSampleRate: 0.5,
});

app.use(Sentry.Handlers.requestHandler() as express.RequestHandler);
app.use(Sentry.Handlers.tracingHandler());
app.use(Sentry.Handlers.errorHandler() as express.ErrorRequestHandler);

export const cronHandler = withSentry(async (event, context) => {
  console.log('EVENT: \n' + JSON.stringify(event, null, 2));
  throw new Error('This error will be raised in Sentry');
  return context.logStreamName;
});

Roadmap

  • Extend this module to support centralised copy on error messages (useful for business users seeing the error, as well as developers investigating the error).
1.2.0

7 months ago

1.1.6

1 year ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.1.2

2 years ago

1.0.22

3 years ago

1.0.26

2 years ago

1.0.25

2 years ago

1.0.24

2 years ago

1.0.23

2 years ago

1.0.27

2 years ago

1.0.19

3 years ago

1.0.21

3 years ago

1.0.20

3 years ago

1.0.18

3 years ago

1.0.17

3 years ago

1.0.16

3 years ago

1.0.15

3 years ago

1.0.14

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago