Raygun4node
Node.JS SDK for Raygun
Install / Use
/learn @MindscapeHQ/Raygun4nodeREADME
Raygun4Node
Raygun.com package for Node, written in TypeScript.
Where is my app API key?
When sending exceptions to the Raygun service, an app API key is required to map the messages to your application.
When you create a new application in your Raygun dashboard, your app API key is displayed within the instructions page. You can also find the API key by clicking the "Application Settings" button in the side bar of the Raygun dashboard.
Getting Started
Install the module with: npm install raygun
const raygun = require('raygun');
const raygunClient = new raygun.Client().init({
apiKey: 'YOUR_API_KEY'
});
You can also use import, which is useful for loading TypeScript definitions. In order to load type definitions, you can use import * as Raygun from 'raygun', or import the Client class directly from the module.
import * as Raygun from 'raygun';
const raygunClient = new Raygun.Client().init({
apiKey: 'YOUR_API_KEY'
});
You can directly send errors to Raygun, either by making the error yourself or passing a caught error.
raygunClient.send(new Error('Something impossible happened!'));
If you use express, you can report the errors that express catches to Raygun by using the middleware.
// Add at the end of the middleware definitions, just above app.listen:
app.use(raygunClient.expressHandler);
You can directly catch errors in your application code and report them to Raygun.
try {
// run some code that might throw an error we want to report
} catch (e) {
raygunClient.send(e);
}
A similar example for Node style callbacks:
function handleResult(error, result) {
if (error) {
raygunClient.send(error);
return;
}
// process result
}
If you're working directly with promises, you can pass raygunClient.send directly to .catch.
const axios = require('axios');
axios
.get('example.com')
.then(handleResponse)
.catch(raygunClient.send);
Expressjs 4.0 and above
The Express documentation says Though not strictly required, by convention you define error-handling middleware last, after other app.use() calls, but that is incorrect. If the app.use(raygunClient.expressHandler); call is not immediately before the app.listen call, then errors will not be handled by Raygun.
Note that the Express middleware handler will pick up and transmit any err objects that reach it. If the app code itself chooses to handle states that result in 4xx/5xx status codes, these will not result in an error payload sent to Raygun.
Documentation
Send
The send() function is asynchronous and returns a Promise of type IncomingMessage.
Note that IncomingMessage can be null if the request was stored because the application was offline.
IncomingMessage is the response from the Raygun API - there's nothing in the body, it's just a status code response. If everything went ok, you'll get a 202 response code.
Otherwise, we return 401 for incorrect API keys, 403 if you're over your plan limits, or anything in the 500+ range for internal errors.
We use the nodejs http/https library to make the POST to Raygun, you can see more documentation about that callback here: https://nodejs.org/api/http.html#http_http_request_options_callback .
You can await the call to obtain the result, or use then/catch.
The default timeout for the transport layer is 5000ms. You can override this value by setting a custom timeout (also in ms) when you initialize the Raygun client:
import * as Raygun from 'raygun';
const raygunClient = new Raygun.Client().init({
apiKey: 'YOUR_API_KEY',
...
timeout: 3000 // defaults to 5000ms
});
Using await
Use await to obtain the IncomingMessage, remember to catch any possible thrown errors from the send() method.
try {
let message = await client.send(error);
} catch (e) {
// error sending message
}
Using then/catch
You can also use then() to obtain the IncomingMessage, as well, use catch() to catch any possible thrown errors from the send() method.
client.send(error)
.then((message) => {
// message sent to Raygun
})
.catch((error) => {
// error sending message
});
Send Parameters
The send() method accepts a series of optional named parameters, defined as follows:
client.send(error, { customData, request, tags, timestamp, userInfo });
Each one of these parameters is optional. They are explained in detail the following sections.
Sending custom data
You can pass custom data in on the Send() function, as the customData parameter. For instance (based off the call in test/raygun_test.js):
client.send(new Error(), { customData: { 'mykey': 'beta' } });
Sending custom data with Expressjs
If you're using the raygunClient.expressHandler, you can send custom data along by setting raygunClient.expressCustomData to a function. The function will get two parameters, the error being thrown, and the request object.
const raygunClient = new raygun.Client().init({apiKey: "YOUR_API_KEY"});
raygunClient.expressCustomData = function (err, req) {
return { 'level': err.level };
};
Sending request data
You can send the request data in the Send() function, as the request parameter. For example:
client.send(new Error(), { request: request });
If you want to filter any of the request data then you can pass in an array of keys to filter when you init the client. For example:
const raygun = require('raygun');
const raygunClient = new raygun.Client().init({ apiKey: 'YOUR_API_KEY', filters: ['password', 'creditcard'] });
Tags
You can add tags to your error in the Send() function, as the tags parameter. For example:
client.send(new Error(), { tags: ['Custom Tag 1', 'Important Error'] });
Tags can also be set globally using setTags
client.setTags(['Tag1', 'Tag2']);
Timestamp
You can specify the exact time your error occurred in the Send() function with the timestamp parameter.
Otherwise, the current time will be used.
This can be useful when combining Raygun together with other logger tools that provide a timestamp.
In milliseconds since epoch:
client.send(new Error(), { timestamp: 1718268992929 });
As Date object:
client.send(new Error(), { timestamp: new Date(2024, 5, 13, 10, 0, 0) });
Customers
You can attach user information to every Raygun Crash Report.
It will be transmitted with the error sent, and a count of affected customers will appear on the dashboard in the error group view. If you provide an email address, and the user has associated a Gravatar with it, their picture will be also displayed.
This package offers two different ways to do that:
- Provide the
userInfoparameter in thesend()method. - Implement the
user(request)method.
User information object
The following properties can be provided as user information:
identifier: Unique identifier for the user is the user identifier.email: User's email address.isAnonymous: Flag indicating if the user is anonymous or not.firstName: User's first name (what you would use if you were emailing them - "Hi {{firstName}}, ...")fullName: User's full name.uuid: Device unique identifier. Useful if sending errors from a mobile device.
All properties are strings except isAnonymous, which is a boolean.
As well, they are all optional. Any other properties will be discarded.
Example:
userInfo = {
identifier: "123",
email: "user@example.com",
isAnonymous: false,
firstName: "First name",
fullName: "Fullname",
uuid: "a25dfe58-8db3-496c-8768-375595139375",
}
For legacy support reasons, you can also provide the string identifier directly as the user information:
raygunClient.send(error, { userInfo: "123" });
userInfo parameter in send()
Provide the userInfo optional parameter in the send() method call:
client.send(new Error(), { userInfo });
This provided user information will take priority over the user(request) method.
Implement raygunClient.user(req)
You can set raygunClient.user to a function that returns the user name or email address of the currently logged in user.
An example, using the Passport.js middleware:
const raygunClient = new raygun.Client().init({apiKey: "YOUR_API_KEY"});
raygunClient.user = function (req) {
if (req.user) {
return {
identifier: req.user.username,
email: req.user.email,
isAnonymous: false,
fullName: req.user.fullName,
firstName: req.user.firstName,
uuid: req.user.deviceID
};
}
}
Param: req: the current request. Returns: The current user's identifier, or an object that describes the user.
Version tracking
Call setVersion(string) on a RaygunClient to set the version of the calling application. This is expected to be of the format x.x.x.x, where x is a positive integer. The version will be visible in the dashboard.
Inner Errors
Starting from 0.10.0 support for inner errors was added. Provide option innerErrorFieldName to specify a field or a function on the error object to use for retrieval of an inner error. Inner errors will be retrieved recursively until there is no more errors. Option innerErrorFieldName defaults to cause which is used in VError, therefore VError is supported out of the box.
Reporting uncaught exceptions
You can enable reporting uncaught excep
