1.0.3 • Published 8 months ago

sentry-javascript v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

sentry-javascript

A generic Javascript SDK based on Self-Hosted Sentry.

Install

Using unpkg CDN

Use the latest version file

<script type="text/javascript" src="https://unpkg.com/sentry-javascript/dist/index.js"></script>

Use the specified version file (recommended)

<script type="text/javascript" src="https://unpkg.com/sentry-javascript@1.0.3/dist/index.js"></script>

Using npm

npm install sentry-javascript --save

Using yarn

yarn add sentry-javascript

Usage

Initialization

ESM

import * as Sentry from 'sentry-javascript'

Sentry.init({
  dsn: '_your_sentry_dsn'
})

CommonJS

const Sentry = require('sentry-javascript')
// const Sentry = require('sentry-javascript/cjs')

Sentry.init({
  dsn: '_your_sentry_dsn'
})

Usage of CDN resource

window.Sentry.init({
  dsn: '_your_sentry_dsn'
})

Capture message

The current operation must be performed after initialization.

Sentry.captureMessage('Something went wrong')

Capture exception

The current operation must be performed after initialization.

try {
  /* something to do */
  aFunctionThatMightFail()
} catch(e) {
  Sentry.captureException(e)
}

Configure scope

The current operation must be performed after initialization.

Sentry.configureScope((scope) => {
  // for instance, add custom tags or inform Sentry about the currently authenticated user
  scope.setTag('my-tag', 'my value')
  scope.setUser({
    id: '666',
    email: 'john.doe@example.com'
  })
})

Method

Initialization

Sentry.init(options)

parameterdescriptiontyperequireddefault value
optionsSentry Initializes the configuration item object of the log. serviceobject-
options parameter configuration items
parameterdescriptiontyperequireddefault value
dsnDSN for the Sentry logging service, the DSN tells the SDK where to send the events (available through the configuration backend).string-
enabledWhether to allow data to be reported.booleantrue
debugIf debugging is enabled, the SDK will attempt to print out useful debugging information if something goes wrong while sending an event. Although enabling debug mode does not cause any security issues, it is usually not recommended to enable debug mode in production environments.booleanfalse
envelopeWhether to use the envelope interface to report data, see Envelopes and Store Endpoint for details.booleantrue
environmentEnvironments that send log data, a version can be associated with multiple environments to separate them in the user interface (e.g. staging vs prod or other similar comparisons).stringproduction
releaseVersion number, suggested format my-project-name@1.0.0.string-
Return value

None

Capture message

Sentry.captureMessage(message, options)

parameterdescriptiontyperequireddefault value
messageMessage to be sent.string-
optionsWhen passed in as a string, it can only be used as a log level, the available values are fatal | error | warning | info | debug; when passed in as an object, it is used as an optional parameter configuration item, see configuration item description for details.string/object-

Return value

Promise\<SentrySDKResponse>

Capture exception

Sentry.captureException(err, options)

parameterdescriptiontyperequireddefault value
errInstance of a standard Error, see MDN for details.object-
optionsAn optional parameter configuration item, see configuration item description for details.object-

Return value

Promise\<SentrySDKResponse>

Configure scope

Sentry.configureScope(callback)

parameterdescriptiontyperequireddefault value
callbackGlobal scope callback function.funciton-

Return value

None

Description of the global Scope object

The following methods are provided.

Set user information

setUser(options)

parameterdescriptiontyperequireddefault value
optionsUser information object, see User Definition for details.object-
Sentry.configureScope((scope) => {
  // clear user information
  scope.setUser(null)
  // set user information
  scope.setUser({
    id: '666',
    email: 'john.doe@example.com'
  })
})
Set tags

setTag(key, value)

parameterdescriptiontyperequireddefault value
keyTag name.string-
valueTag value.string-
Sentry.configureScope((scope) => {
  scope.setTag('my-tag', 'my value')
})
Remove tag

removeTag(key)

parameterdescriptiontyperequireddefault value
keyTag name.string-
Sentry.configureScope((scope) => {
  scope.removeTag('my-tag')
})
Set extra data

setExtra(key, value)

parameterdescriptiontyperequireddefault value
keyExtra data name.string-
valueExtra data value.any-
Sentry.configureScope((scope) => {
  scope.setExtra('my-extra', {
    'key1': 'value1',
    'key2': 'value2'
  })
})
Remove extra data

removeExtra(key)

parameterdescriptiontyperequireddefault value
keyExtra data name.string-
Sentry.configureScope((scope) => {
  scope.removeExtra('my-extra')
})
Set log level

setLevel(level)

parameterdescriptiontyperequireddefault value
levelLog level, the available values are fatal | error | warning | info | debugstring-
Sentry.configureScope((scope) => {
  scope.setLevel('debug')
  Sentry.captureMessage('Something went wrong')
})
Add breadcrumb record

addBreadcrumb | parameter | description | type | required | default value | |---|---|---|---|---| | breadcrumb | breadcrumb record | object | ✅ | - |

Sentry.configureScope((scope) => {
  scope.addBreadcrumb({
    "timestamp": "2023-06-19T06:56:32.306Z",
    "message": "Something happened",
    "category": "log",
    "data": {
      "foo": "bar",
      "blub": "blah"
    }
  })
})
Clear breadcrumb records

clearBreadcrumbs

Sentry.configureScope((scope) => {
  // clear the previous scope breadcrumb records
  scope.clearBreadcrumbs()
  // add breadcrumb record
  scope.addBreadcrumb({
    "timestamp": "2023-06-19T06:56:55.266Z",
    "type": "navigation",
    "data": {
      "from": "/login",
      "to": "/dashboard"
    }
  })
})
Clear the global scope configuration

clear()

Sentry.configureScope((scope) => {
  // clear the previous scope configuration
  scope.clear()
  // set new tag
  scope.setTag('new-tag', 'new value')
})

The options of capture methods

This configuration note is only for Sentry.captureMessage and Sentry.captureException.

parameterdescriptiontyperequireddefault value
event_idHexadecimal string representing a uuid4 value. The length is exactly 32 characters. Dashes are not allowed. Has to be lowercase.string-
messageMessage to be sent,see Message Definition for details. If this parameter is configured with a legal value, it will take precedence over the message parameter of the Sentry.captureMessage method.string/object-
levelLog level, the available values are fatal | error | warning | info | debug. The default value of the Sentry.captureMessage method is info, and the default value of the Sentry.captureException method is error.string-
typeEvent type for recording errors, see Type Definition for details.stringevent
exceptionSpecify the exception or error that occurred in the program, see Exception Definition for details.object-
requestThe Request interface contains information on a HTTP request related to the event. In client SDKs, this can be an outgoing request, or the request that rendered the current web page, see Request Definition for details.object-
userCurrent authenticated user information, see User Definition for details.object{ip_address: '{{auto}}'}
tagsA map or list of tags for this event. Each tag must be less than 200 characters, see Event Payloads for details.object-
extraAn arbitrary mapping of additional metadata to store with the event, see Event Payloads for details.object-
breadcrumbsA list of breadcrumb records to describe the track of events,see Breadcrumbs Definition for details.array-

Return value description of capture method

Before reading this return value description, you need to understand the predefined SDK envelope.

This return value description is only for results sent successfully using Sentry.captureMessage and Sentry.captureException.

keydescriptiontype
idEvent identifier.string

SDK envelope

The predefined SDK envelope is essentially a data of type object, and the following is a description of its structure.

keydescriptiontypedefault value
codeError code.number-
dataCommunication data, any meaningful data will be given in this field.objectnull
messageTip messagestring-

Error Code Description

error codedescription
0Success
400Bad request. Usually it is some call and passed parameter error that causes.
413Request content too large. For example, if the data sent is too large, the current SDK limits it to a maximum of 20MB.
429Too many requests. It is usually the service itself that responds because the concurrent load is too high.
500Network errors. Usually some network connection problems, such as request timeouts.
10001The current SDK is set to disable sending data.

How to open the envelope properly to get the data

This is a demo to get the event id.

import * as Sentry from 'sentry-javascript'

const getEventId = async () => {
  const res = await Sentry.captureMessage('Something went wrong')
  let eventId = ''
  if (res.code === 0 && res.data && res.data.id) {
    eventId = res.data.id
  }
  return eventId
}
const eventId = await getEventId()
console.log('current event id is: ' + eventId)
// output `current event id is: xxxxxxxx`

TypeScript Support

The module naturally supports TypeScript, and here is a demo.

import * as Sentry from 'sentry-javascript'
import type { SentrySDKResponse } from 'sentry-javascript'

const getCaptureStatus = async (): Promise<string> => {
  const res: SentrySDKResponse = await Sentry.captureMessage('Something went wrong')
  let status = 'fail'
  if (res.code === 0 && res.data && res.data.id) {
    status = 'success'
  }
  return status
}
const status = await getCaptureStatus()
console.log('current data capture is ' + status)
// output `current data capture is success`

License

sentry-javascript is MIT licensed.