Skip to content
This repository has been archived by the owner on Dec 4, 2018. It is now read-only.

Express example #93

Merged
merged 6 commits into from
Mar 31, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions examples/express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Express Example

This example shows how you can use the Bugsnag Node notifier with Express apps.

## Demonstrates

- [Configuring the client](bugsnag.js#L4-L9)
- Registering middleware
- [Request handler](index.js#L10-L12)
- [Error handler](index.js#L66-L69)
- [Sending a custom error](index.js#L49-L57)
- Handling errors from promises
- [Automatically](bugsnag.js#L11-L20)
- [Manually](index.js#L60-L63)
- Attaching session/user info to errors
- [Registering your app's middleware](index.js#L14-L17)
- [Setting the request data](api.js#L22-L31)

## Setup

This example gives you the ability to send request to a single endpoint, which depending on
[the parameters](index.js#L19-39), will throw different kinds of errors.

1. Clone the repository

```
$ git clone https://github.com/bugsnag/bugsnag-node.git
```

2. Add your project API key

Open the `bugsnag.js` file and replace `API-KEY-GOES-HERE` with your own API key.

```js
bugsnag.register("API-KEY-GOES-HERE");
```

3. Install dependencies

You can use `npm install` or `yarn install` to install the dependencies.

4. Start the server

Again, you can use `npm start` or `yarn start` to start the webserver on port 3000 (by default).
36 changes: 36 additions & 0 deletions examples/express/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const bugsnag = require("./bugsnag");

function attemptLogin(username, password) {
return new Promise((resolve, reject) => {
if (username === "crash") {
// Obviously you wouldn't expect to see this in your production app, but here is an example of what
// you might have underlying your database abstraction.
reject(new Error(`Unable to connect to database`));
} else {
if (username === password) {
resolve({
id: 1,
name: username,
});
} else {
resolve(null);
}
}
});
}

function loadSession(req, res, next) {
// We may not always be reporting errors manually. What happens if there's an error we didn't anticipate?
// In that case we can attach some user data to the request, so we know which user was affected by the error.
bugsnag.requestData.user = {
id: 1,
name: "james",
plan: "beast-mode",
};
next(null);
}

module.exports = {
attemptLogin,
loadSession,
};
22 changes: 22 additions & 0 deletions examples/express/bugsnag.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const bugsnag = require("bugsnag");
const unhandledRejection = require("unhandled-rejection");

// Here we register the Bugsnag client using our project's API key, and optionally pass our
// Bugsnag configuration. For example, we can enable `sendCode` so we're able to see the code
// within our app straight from the Bugsnag error report page.
bugsnag.register("API-KEY-GOES-HERE", {
sendCode: true,
});

// When it comes to unhandled rejections (from Promises) within our app, we can use a library
// called "unhandled-rejection" to do all the heavy lifting. This library gives us the ability to
// catch rejections from within multiple types of Promise implementations.
let rejectionEmitter = unhandledRejection({
timeout: 20
});

rejectionEmitter.on("unhandledRejection", (error, promise) => {
bugsnag.notify(error);
});

module.exports = bugsnag;
71 changes: 71 additions & 0 deletions examples/express/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
const express = require("express");
const bodyParser = require("body-parser");
const bugsnag = require("./bugsnag");
const { attemptLogin, loadSession } = require("./api");

const app = express();

app.use(bodyParser.json());

// We need to add the Bugsnag request handler middleware, so when an async error occurs we're
// able to notify any middleware in the chain (in this case the Bugsnag error handler).
app.use(bugsnag.requestHandler);

// In your application, it's likely you have some form of session system. For this example, we're
// just adding some fake user information to any unhandled errors, so we can track what kind of
// impact our *bad* code is having on our user base.
app.use(loadSession);

// Our sample login endpoint for this example app. You can try this endpoint out for yourself.
//
// Failed login attempt
//
// ```
// curl \
// -X POST \
// -H "Content-Type: application/json" \
// -d '{"username":"admin","password":"xyz"}'
// http://localhost:3000/login`
// ```
//
// Unable to connect to database
//
// ```
// curl \
// -X POST \
// -H "Content-Type: application/json" \
// -d '{"username":"crash","password":"xyz"}' \
// http://localhost:3000/login
// ```
app.post("/login", (req, res, next) => {
const { username, password } = req.body;
attemptLogin(username, password)
.then(user => {
if (user) {
res.send("Logged in!");
} else {
res.status(400).send("Invalid username or password.");

bugsnag.notify(new Error("Failed login attempt"), {
// Maybe you have a system in place to block a particular IP address, or account if there are
// too many failed attempts within a specified time period? Why not send this event to Bugsnag?
attempt: {
username,
ip: "192.168.100.16",
tries: 4,
},
});
}
})
// To allow errors to be passed to the appropriate error handler middleware, we can simply pass the
// next callback to the `catch` part of our Promise chain. Basically all this means is that unhandled
// errors in your Promises are not lost.
.catch(next);
});

// We also need to add the bugsnag error handler middleware, which catches any unhandled errors
// within your routes (like the one above) and sends them to Bugsnag, along with the request information
// the error occurred in, to make debugging errors *that* much easier.
app.use(bugsnag.errorHandler);

app.listen(process.env.PORT || 3000);
11 changes: 11 additions & 0 deletions examples/express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"dependencies": {
"body-parser": "^1.16.1",
"bugsnag": "^1.9.1",
"express": "^4.14.1",
"unhandled-rejection": "^1.0.0"
},
"scripts": {
"start": "node ."
}
}
Loading