Skip to content

Instantly share code, notes, and snippets.

@dukejones
Created March 13, 2020 05:56
Show Gist options
  • Save dukejones/d160a1b2051ff7c1a485bdcf966f1bcc to your computer and use it in GitHub Desktop.
Save dukejones/d160a1b2051ff7c1a485bdcf966f1bcc to your computer and use it in GitHub Desktop.
Log errors and messages to Rollbar from a Cloudflare Worker
import ErrorStackParser from 'error-stack-parser'
const ROLLBAR_ACCESS_TOKEN = '[ACCESS TOKEN]'
var rollbarUrl = `https://api.rollbar.com/api/1/item/`
// https://github.com/rollbar/rollbar.js/blob/master/src/errorParser.js
function Frame(stackFrame: ErrorStackParser.StackFrame) {
var data:any = {};
// data._stackFrame = stackFrame;
data.filename = stackFrame.fileName;
data.lineno = stackFrame.lineNumber;
data.colno = stackFrame.columnNumber;
data.method = stackFrame.functionName;
data.args = stackFrame.args;
return data;
}
export const rollbarError = async (error: Error, description?: string|null) => {
const stack = ErrorStackParser.parse(error)
const rollbarBody = {
"access_token": ROLLBAR_ACCESS_TOKEN,
"data": {
"environment": "development",
"body": {
"trace": {
"frames": stack.map( stackFrame => Frame(stackFrame) ),
"exception": {
"class": error.name,
"message": error.message
}
}
}
}
}
if (description) {
Object.assign(rollbarBody.data.body.trace.exception, {description: description})
}
const rollbarRequest = new Request(rollbarUrl, {
method: 'POST',
body: JSON.stringify(rollbarBody)
})
const rollbarResponse = await fetch(rollbarRequest)
return rollbarResponse
}
export const rollbarMessage = async (message: string, attributes: {}|null) => {
const rollbarBody = {
"access_token": ROLLBAR_ACCESS_TOKEN,
"data": {
"environment": "development",
"body": {
"message": {
"body": message,
}
}
}
}
if (attributes) {
Object.assign(rollbarBody.data.body.message, attributes)
}
const rollbarRequest = new Request(rollbarUrl, {
method: 'POST',
body: JSON.stringify(rollbarBody)
})
const rollbarResponse = await fetch(rollbarRequest)
return rollbarResponse
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment