Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | import * as Sentry from "@sentry/react";
import { AxiosError } from "axios";
import { useEffect } from "react";
import {
createRoutesFromChildren,
matchRoutes,
useLocation,
useNavigationType,
} from "react-router-dom";
Sentry.init({
environment: process.env.VITE_ENVIRONMENT,
release: process.env.VITE_ENVIRONMENT,
debug: false,
ignoreErrors: [
"CanceledError",
// Ignore users network-related errors that are not valuable and crowd the view on real issues.
"NetworkError",
"Non-Error promise rejection captured with value: Timeout",
"Non-Error promise rejection captured with value: Object Not Found Matching Id",
'Could not load "util".',
"Can't find variable: logMutedMessage", // caused by the browser, not in our code
// Flagsmith throws these when a feature flag key is queried before the SDK is initialised
// or when a flag name doesn't exist in the current environment. They are harmless and not
// actionable. The unhandledrejection listener in handlerCallback also suppresses them, but
// Sentry registers its own global handlers during Sentry.init() so an explicit filter here
// ensures they are dropped even if the rejection is captured before our listener fires.
/feature named .* was not found/i,
],
// Ignore errors originating from third-party scripts (outside our control)
denyUrls: [/recaptcha__.*\.js/i, /gstatic\.com\/recaptcha/i],
dsn: process.env.VITE_SENTRY_DSN,
integrations: [
Sentry.browserTracingIntegration(),
Sentry.browserApiErrorsIntegration(),
// Sentry.browserProfilingIntegration(),
Sentry.reactRouterV6BrowserTracingIntegration({
useEffect,
useLocation,
useNavigationType,
createRoutesFromChildren,
matchRoutes,
}),
// Sentry.replayIntegration(),
// Sentry.replayCanvasIntegration(), //Needed to enable replay for canvas elements
],
// Tracing
tracesSampleRate: 0.0,
//Profiling
profilesSampleRate: 0.0,
replaysSessionSampleRate: 0.0,
replaysOnErrorSampleRate: 0.0,
beforeSend: (event, hint) => {
const { request, tags } = event;
const url = request?.url || "";
const environment = tags?.environment;
const originalError = hint?.originalException;
const localHosts = ["local.", "localhost", "127.0.0.1", "://local"];
const isLocalUrl = localHosts.some((host) => url.includes(host));
const isLocalEnv = environment === "development";
if (isLocalUrl || isLocalEnv) {
return null; // Discard the event
}
// Filter out XMLHttpRequest errors ONLY when we have strong evidence they're caused by
// navigation-related request aborts. We need to be conservative here because genuine
// XHR errors (network failures, service outages) CAN impact user experience and should be reported.
const exceptionValue = event.exception?.values?.[0];
const breadcrumbs = event.breadcrumbs || [];
if (exceptionValue) {
const { value, type } = exceptionValue;
// Filter XMLHttpRequestProgressEvent errors if it matches the abort pattern:
// 1. It's explicitly a ProgressEvent or XMLHttpRequestProgressEvent error
// 2. There's an aborted XHR in breadcrumbs (status_code: 0)
if (
value?.includes("ProgressEvent") ||
type === "ProgressEvent" ||
type === "XMLHttpRequestProgressEvent"
) {
// Look for evidence of session expiration flow: 401 error → navigation → aborted XHR
const has401Error = breadcrumbs.some(
(crumb) =>
crumb.category === "xhr" && crumb.data?.status_code === 401,
);
const hasNavigationToLogin = breadcrumbs.some(
(crumb) =>
crumb.category === "navigation" && crumb.data?.to === "/login",
);
const hasAbortedXHR = breadcrumbs.some(
(crumb) => crumb.category === "xhr" && crumb.data?.status_code === 0,
);
// If we see the full session-expiration pattern, some 401 comes from other paths not just /login
if (has401Error && hasNavigationToLogin && hasAbortedXHR) {
console.log(
"[Sentry] Filtering XHR abort due to session expiration redirect",
);
return null; // discard
}
// Otherwise, if it's just an aborted XHR (status 0) — conservative filter
if (hasAbortedXHR) {
console.log("[Sentry] Filtering aborted XHR with status 0");
return null;
}
}
// Filter Android WebView errors where the Java bridge object is destroyed or buggy
// This commonly occurs in WebView environments (Instagram in-app browser, Facebook browser, etc.)
// when the WebView is being destroyed or the bridge is in an inconsistent state.
// 1) "Java object is gone": native bridge has been garbage collected.
// 2) "Error invoking post: Method not found": native bridge method is missing/inaccessible.
// This is not actionable as it's a WebView lifecycle/environment issue.
if (
value?.includes("Java object is gone") ||
value?.includes("postMessage: Java object") ||
value?.includes("Error invoking post: Method not found")
) {
// Additional validation: check if this is from a known WebView browser
const userAgent = event.request?.headers?.["User-Agent"] || "";
const isWebView =
userAgent.includes("Instagram") ||
userAgent.includes("FBAN") || // Facebook App
userAgent.includes("FBAV") || // Facebook App Version
userAgent.includes("wv"); // Generic WebView indicator
if (isWebView) {
console.log(
"[Sentry] Filtering Android WebView Java bridge error (object gone or method not found)",
);
return null; // Discard the event
}
}
}
// Filter out expected 404s on CSV export endpoints (no data to export)
const hasCsvExport404 = breadcrumbs.some(
(crumb) =>
crumb.category === "xhr" &&
crumb.level === "warning" &&
crumb.data?.url?.includes(".csv") &&
crumb.data?.status_code === 404,
);
if (
hasCsvExport404 &&
event.exception?.values?.[0]?.value?.includes("404")
) {
return null; // Expected error - no data to export
}
// Ignore non-critical errors caused by external factors:
// 1. runtime.sendMessage(): thrown by browser extensions when the target tab is unavailable
// 2. window.webkit.messageHandlers: thrown in browsers that aren't iOS WKWebViews
if (
event.exception?.values?.some(
(v) =>
v.value?.includes("window.webkit.messageHandlers") ||
v.value?.includes("runtime.sendMessage"),
)
) {
return null; // Ignore DuckDuckGo WKWebView errors
}
if (event.exception?.values?.[0]?.value?.includes("invalid origin")) {
return null;
}
if (
event.exception?.values?.some(
(v) => v.type === "NotFoundError" && v?.value?.includes("removeChild"),
)
) {
return null;
}
// FilterOut known third-party "invalid origin" errors that surface as unhandled
// promise rejections on privacy-focused browsers (e.g. DuckDuckGo iOS).
// These originate outside our codebase and should not crash the application.
if (originalError instanceof Error) {
if (originalError.message === "invalid origin") {
return null;
}
}
// Fallback: sometimes message is only in event
if (event.exception?.values?.some((e) => e.value === "invalid origin")) {
return null;
}
// Axios network errors are sometimes caught and sometimes unhandled.
// If they are caught elsewhere, they won’t trigger the unhandledrejection listener,
// so we filter them here in beforeSend to avoid noisy Sentry reports.
if (originalError instanceof AxiosError) {
if (originalError.message === "Network Error") {
return null;
}
const statusCode = originalError.response?.status;
const endpointPath = originalError.config?.url?.split("?")[0] || "";
// Ignore expected 404s from policy pages like /terms_of_service where
// the endpoint may legitimately return 404 (e.g. document not configured)
if (statusCode === 404 && endpointPath.includes("terms_of_service")) {
return null;
}
// Enrich API errors (404, 422, and all other status codes) with detailed context
// This helps us debug issues by seeing the full request/response details in Sentry
if (statusCode) {
// Add request context
event.contexts = event.contexts || {};
event.contexts.request_details = {
url: originalError.config?.url,
method: originalError.config?.method?.toUpperCase(),
baseURL: originalError.config?.baseURL,
params: originalError.config?.params,
};
// Add response context
event.contexts.response_details = {
status: statusCode,
statusText: originalError.response?.statusText,
data: serializeWithLimit(originalError.response?.data),
headers: serializeHeaders(originalError.response?.headers),
};
// Add tags for easy filtering in Sentry UI
event.tags = event.tags || {};
event.tags.api_error = true;
event.tags.status_code = statusCode;
event.tags.http_method = originalError.config?.method?.toUpperCase();
// Extract endpoint path (without query params or base URL)
const endpoint = endpointPath || "unknown";
event.tags.endpoint = endpoint;
// Set fingerprint to group similar errors together
// This groups errors by: endpoint + status code
event.fingerprint = [endpoint, String(statusCode)];
}
}
// Filter fetch network errors ("Failed to fetch")
// This is the fetch equivalent of Axios "Network Error".
// Usually caused by connectivity issues, or aborted requests.
if (
originalError instanceof TypeError &&
originalError.message === "Failed to fetch"
) {
return null;
}
// Filter out errors from browser extensions
if (event.exception) {
const values = event.exception.values || [];
// Check if error is from an extension
const isExtensionError = values.some((value) => {
const message = value.value || "";
return (
message.includes("browser.storage") ||
message.includes("chrome-extension") ||
message.includes("moz-extension")
);
});
if (isExtensionError) {
return null;
}
}
// Ignore Cloudflare RUM parse errors
if (
originalError instanceof SyntaxError &&
originalError.message.includes("JSON Parse error")
) {
// Optional: check endpoint
if (originalError.stack?.includes("/cdn-cgi/rum")) {
return null; // drop
}
}
return event;
},
});
const serializeWithLimit = (data: any, maxLength = 500) => {
if (!data) return null;
try {
const serialized = typeof data === "string" ? data : JSON.stringify(data);
if (serialized.length > maxLength) {
return serialized.substring(0, maxLength) + "... (truncated)";
}
return serialized;
} catch (error) {
return "[Unable to serialize data]";
}
};
const serializeHeaders = (headers: any) => {
if (!headers) return null;
try {
return JSON.stringify(headers);
} catch (error) {
return "[Unable to serialize headers]";
}
};
|