Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0cad520
add response to core event type
gingerbenw Dec 15, 2025
44f3e02
feat: add plugin-http-errors package
gingerbenw Dec 15, 2025
8954bc3
test: :white_check_mark: add end to end tests for http errors
gingerbenw Dec 15, 2025
b7538b7
integrate shared tracker
gingerbenw Dec 15, 2025
be68044
test: test xhr requests
gingerbenw Dec 15, 2025
b141dad
handle hxr requests
gingerbenw Dec 16, 2025
ec3e639
fix http errors testing
gingerbenw Dec 16, 2025
7013ce6
enhancement: move helpers to separate modules
gingerbenw Dec 16, 2025
66dac50
handle redacted keys for headers and params
gingerbenw Dec 17, 2025
feee16d
redact query string parameters on URLs
gingerbenw Dec 17, 2025
f253001
skip tests on unsupported browsers
gingerbenw Dec 17, 2025
43b4790
Report and redact request headers
gingerbenw Dec 17, 2025
f10842a
require set
gingerbenw Dec 17, 2025
f1cad91
remove use of Object.entries
gingerbenw Dec 18, 2025
c74c00c
fix unit tests
gingerbenw Dec 18, 2025
98557f9
change: handle headers in request-tracker
gingerbenw Dec 19, 2025
8f496ca
docs: update README
gingerbenw Dec 19, 2025
961e058
simplify return values from request tracker plugin
gingerbenw Dec 19, 2025
65cd851
Apply suggestion from @Copilot
gingerbenw Dec 19, 2025
d217fdc
Update test/browser/features/http_errors.feature
gingerbenw Dec 19, 2025
1e0a150
enhancement: redact response in events
gingerbenw Dec 19, 2025
af98955
refactor: reorder http errors operations
gingerbenw Dec 19, 2025
172bb79
test: add tests for POST requests
gingerbenw Dec 19, 2025
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
7 changes: 4 additions & 3 deletions bin/local-test-util
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ async function buildNotifiers (notifier) {
async function packNotifiers (notifier) {
const notifiers = notifier
? [ notifier ]
: [ 'js', 'browser', 'node', 'web-worker', 'plugin-angular', 'plugin-react', 'plugin-vue' ]
: [ 'js', 'browser', 'node', 'web-worker', 'plugin-angular', 'plugin-react', 'plugin-vue', 'plugin-http-errors' ]
for (const n of notifiers) {
let packageLocation = `packages/${n}/`
if (n === 'plugin-angular') packageLocation += 'dist/'
Expand All @@ -131,7 +131,7 @@ async function packNotifiers (notifier) {

async function installNotifiers (notifier) {
trace('install notifiers')
if (notifier && ![ 'browser', 'plugin-vue', 'plugin-react', 'web-worker' ].includes(notifier)) return
if (notifier && ![ 'browser', 'plugin-vue', 'plugin-react', 'web-worker', 'plugin-http-errors' ].includes(notifier)) return
await ex(`npm`, [
`install`,
`--no-package-lock`,
Expand All @@ -144,7 +144,8 @@ async function installNotifiers (notifier) {
`../../../../bugsnag-browser-${require('../packages/browser/package.json').version}.tgz`,
`../../../../bugsnag-web-worker-${require('../packages/web-worker/package.json').version}.tgz`,
`../../../../bugsnag-plugin-react-${require('../packages/plugin-react/package.json').version}.tgz`,
`../../../../bugsnag-plugin-vue-${require('../packages/plugin-vue/package.json').version}.tgz`
`../../../../bugsnag-plugin-vue-${require('../packages/plugin-vue/package.json').version}.tgz`,
`../../../../bugsnag-plugin-http-errors-${require('../packages/plugin-http-errors/package.json').version}.tgz`
]
), {
cwd: `${__dirname}/../test/browser/features/fixtures`
Expand Down
3 changes: 2 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ module.exports = {
'plugin-inline-script-content',
'plugin-simple-throttle',
'plugin-console-breadcrumbs',
'plugin-browser-session'
'plugin-browser-session',
'plugin-http-errors'
], {
testEnvironment: '<rootDir>/jest/FixJSDOMEnvironment.js'
}),
Expand Down
21 changes: 21 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/core/event.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { App, Device, Event, Request, Breadcrumb, User, Session, FeatureFlag } from './types'
import { App, Device, Event, Request, Response, Breadcrumb, User, Session, FeatureFlag } from './types'
import { Error } from './types/event'

interface HandledState {
Expand Down Expand Up @@ -40,6 +40,7 @@ export default class EventWithInternals extends Event {
app: App
device: Device
request: Request
response: Response
breadcrumbs: Breadcrumb[]
context: string | undefined
correlation: { spanId: string, traceId: string } | undefined
Expand Down
2 changes: 2 additions & 0 deletions packages/core/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class Event {
this.app = {}
this.device = {}
this.request = {}
this.response = {}

this.breadcrumbs = []
this.threads = []
Expand Down Expand Up @@ -120,6 +121,7 @@ class Event {
app: this.app,
device: this.device,
request: this.request,
response: this.response,
breadcrumbs: this.breadcrumbs,
context: this.context,
groupingHash: this.groupingHash,
Expand Down
3 changes: 2 additions & 1 deletion packages/core/lib/json-payload.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ const jsonStringify = require('@bugsnag/safe-json-stringify')
const EVENT_REDACTION_PATHS = [
'events.[].metaData',
'events.[].breadcrumbs.[].metaData',
'events.[].request'
'events.[].request',
'events.[].response'
]

module.exports.event = (event, redactedKeys) => {
Expand Down
7 changes: 7 additions & 0 deletions packages/core/types/common.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ interface Request {
[key: string]: any
}

interface Response {
statusCode: number
headers: { [key: string]: unknown }
body?: string
bodyLength?: number
}

export interface User {
id?: string
email?: string
Expand Down
2 changes: 2 additions & 0 deletions packages/core/types/event.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
App,
Device,
Request,
Response,
Logger,
User,
Thread,
Expand All @@ -23,6 +24,7 @@ declare class Event {
public app: App
public device: Device
public request: Request
public response: Response

public errors: Error[];
public breadcrumbs: Breadcrumb[]
Expand Down
19 changes: 19 additions & 0 deletions packages/plugin-http-errors/LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Copyright (c) 2025 Bugsnag

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
45 changes: 45 additions & 0 deletions packages/plugin-http-errors/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# @bugsnag/plugin-http-errors

A [@bugsnag/js](https://github.com/bugsnag/bugsnag-js) plugin for HTTP error handling.

## Installation

```sh
npm install --save @bugsnag/plugin-http-errors
# or
yarn add @bugsnag/plugin-http-errors
```

## Usage

```js
import Bugsnag from '@bugsnag/js'
import createHttpErrorPlugin from '@bugsnag/plugin-http-errors'

const plugin = createHttpErrorPlugin({
httpErrorCodes: [401, { min: 404, max: 499 }], // handle individual error codes or ranges of error codes
maxRequestSize: 5_000, // don't capture requests over 5kb
onHttpError: ({ request, response }) => {
// Only handle 5xx errors
if (response.statusCode < 500 || response.statusCode > 599) return false

// Exclude specific domains
if (request.url.indexOf('redacted.domain.com') === 0) return false

// Update properties on the reported request and response
request.url = '[REDACTED]'
response.statusCode = 418

return true // return value will determine whether the error is reported
}
})

Bugsnag.start({
apiKey: 'YOUR_API_KEY',
plugins: [plugin]
})
```

## License

This package is free software released under the MIT License. See [LICENSE.txt](./LICENSE.txt) for details.
169 changes: 169 additions & 0 deletions packages/plugin-http-errors/http-errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* @bugsnag/plugin-http-errors
* A plugin to automatically capture and report HTTP errors
*/

const extractDomain = require('./lib/extract-domain')
const parseQueryParams = require('./lib/parse-query-params')
const redactQueryParameters = require('./lib/redact-query-parameters')
const shouldCaptureStatusCode = require('./lib/should-capture-status-code')
const truncate = require('./lib/truncate')

const DEFAULT_HTTP_ERROR_CODES = [{ min: 400, max: 599 }]
const DEFAULT_MAX_REQUEST_SIZE = 5000

/**
* Creates the HTTP errors plugin with configuration
* @param {Object} config - Plugin configuration
* @param {Array|Object|number} config.httpErrorCodes - Error codes to capture
* @param {number} config.maxResponseSize - Maximum response body size to capture
* @param {number} config.maxRequestSize - Maximum request body size to capture
* @param {Function} config.onHttpError - Callback for intercepting HTTP errors
* @returns {Object} Bugsnag plugin
*/
module.exports = (config = {}, global = window) => {
const {
httpErrorCodes = DEFAULT_HTTP_ERROR_CODES,
maxRequestSize = DEFAULT_MAX_REQUEST_SIZE,
onHttpError
} = config

// Normalize httpErrorCodes to an array
const normalizedStatusCodes = Array.isArray(httpErrorCodes) ? httpErrorCodes : [httpErrorCodes]

let restoreFunctions = []
const plugin = {
name: 'httpErrors',
load: (client) => {
// Try to get existing request tracker
let requestTrackerPlugin = client.getPlugin('requestTracker')

// Auto-load request tracker if not present
if (!requestTrackerPlugin) {
try {
const { createRequestTrackerPlugin } = require('@bugsnag/request-tracker')
const trackerPlugin = createRequestTrackerPlugin([], global)
client._loadPlugin(trackerPlugin)
requestTrackerPlugin = client.getPlugin('requestTracker')
} catch (error) {
client._logger.warn('Failed to auto-load request tracker, using direct fetch patching:', error.message)
}
}

// Use shared request tracker if available
if (requestTrackerPlugin) {
const { fetchTracker, xhrTracker } = requestTrackerPlugin

if (fetchTracker) {
restoreFunctions.push(fetchTracker._restore)
fetchTracker.onStart((startContext) => {
return {
onRequestEnd: (endContext) => {
handleHttpError(startContext, endContext)
}
}
})
}
if (xhrTracker) {
restoreFunctions.push(xhrTracker._restore)
xhrTracker.onStart((startContext) => {
return {
onRequestEnd: (endContext) => {
handleHttpError(startContext, endContext)
}
}
})
}
}

function handleHttpError (startContext, endContext) {
// Check if we should capture this status code
if (!shouldCaptureStatusCode(normalizedStatusCodes, endContext.status)) return

try {
// Extract request information
const url = startContext.url
const requestParams = parseQueryParams(url)
const method = startContext.method
const domain = extractDomain(url)

// Create request and response objects for callback
const requestObj = {
url: startContext.url,
httpMethod: startContext.method,
headers: startContext.headers,
params: requestParams,
body: startContext.body,
bodyLength: startContext.body ? startContext.body.length : undefined
}
const responseObj = {
statusCode: endContext.status,
headers: endContext.headers,
body: endContext.body,
bodyLength: endContext.body ? endContext.body.length : undefined
}

// Call onHttpError callback if provided
if (onHttpError) {
const result = onHttpError({ request: requestObj, response: responseObj })

// If onHttpError returns false, don't capture
if (result === false) {
return
}
}

// Truncate request body
if (requestObj.body) {
requestObj.body = truncate(requestObj.body, maxRequestSize)
}

// Truncate response body - XHR only
if (responseObj.body) {
responseObj.body = truncate(responseObj.body, maxRequestSize)
}

// Strip query parameters from URL
if (requestObj.url !== '[REDACTED]') {
requestObj.url = redactQueryParameters(requestObj.url, client._config.redactedKeys)
}

// Create error and notify
const error = new Error(`${responseObj.statusCode}: ${requestObj.url}`)
error.name = 'HTTPError'

const handledState = {
severity: 'error',
unhandled: true,
severityReason: { type: 'httpError' }
}

const event = client.Event.create(
error,
true,
handledState,
'http errors plugin',
0
)

event.request = requestObj
event.response = responseObj
event.context = `${method} ${domain}`

client._notify(event)
} catch (err) {
client._logger.error('Failed to process HTTP error:', err.message)
}
}
}
}

if (process.env.NODE_ENV !== 'production') {
plugin.destroy = () => {
restoreFunctions.forEach(fn => fn())
restoreFunctions = []
}
}

return plugin
}
13 changes: 13 additions & 0 deletions packages/plugin-http-errors/lib/extract-domain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Extract domain from URL
* @param {string} url - URL string
* @returns {string} Domain
*/
module.exports = function (url) {
try {
const urlObj = new URL(url)
return urlObj.host
} catch (e) {
return 'unknown'
}
}
Loading