-
Notifications
You must be signed in to change notification settings - Fork 256
Create http errors plugin #2639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gingerbenw
wants to merge
23
commits into
integration/http-errors
Choose a base branch
from
PLAT-12567/http-errors-plugin
base: integration/http-errors
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+9,327
−17
Open
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 44f3e02
feat: add plugin-http-errors package
gingerbenw 8954bc3
test: :white_check_mark: add end to end tests for http errors
gingerbenw b7538b7
integrate shared tracker
gingerbenw be68044
test: test xhr requests
gingerbenw b141dad
handle hxr requests
gingerbenw ec3e639
fix http errors testing
gingerbenw 7013ce6
enhancement: move helpers to separate modules
gingerbenw 66dac50
handle redacted keys for headers and params
gingerbenw feee16d
redact query string parameters on URLs
gingerbenw f253001
skip tests on unsupported browsers
gingerbenw 43b4790
Report and redact request headers
gingerbenw f10842a
require set
gingerbenw f1cad91
remove use of Object.entries
gingerbenw c74c00c
fix unit tests
gingerbenw 98557f9
change: handle headers in request-tracker
gingerbenw 8f496ca
docs: update README
gingerbenw 961e058
simplify return values from request tracker plugin
gingerbenw 65cd851
Apply suggestion from @Copilot
gingerbenw d217fdc
Update test/browser/features/http_errors.feature
gingerbenw 1e0a150
enhancement: redact response in events
gingerbenw af98955
refactor: reorder http errors operations
gingerbenw 172bb79
test: add tests for POST requests
gingerbenw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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' | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.