1// DO NOT IMPORT window.config HERE!
2// to make sure the error handler always works, we should never import `window.config`, because
3// some user's custom template breaks it.
4
5// This sets up the URL prefix used in webpack's chunk loading.
6// This file must be imported before any lazy-loading is being attempted.
7__webpack_public_path__ = `${window.config?.assetUrlPrefix ?? '/assets'}/`;
8
9// Ignore external and some known internal errors that we are unable to currently fix.
10function shouldIgnoreError(err) {
11 const assetBaseUrl = String(new URL(__webpack_public_path__, window.location.origin));
12
13 if (!(err instanceof Error)) return false;
14 // If the error stack trace does not include the base URL of our script assets, it likely came
15 // from a browser extension or inline script. Ignore these errors.
16 if (!err.stack?.includes(assetBaseUrl)) return true;
17 // Ignore some known internal errors that we are unable to currently fix (eg via Monaco).
18 const ignorePatterns = [
19 '/assets/js/monaco.', // https://codeberg.org/forgejo/forgejo/issues/3638 , https://github.com/go-gitea/gitea/issues/30861 , https://github.com/microsoft/monaco-editor/issues/4496
20 ];
21 for (const pattern of ignorePatterns) {
22 if (err.stack?.includes(pattern)) return true;
23 }
24 return false;
25}
26
27const filteredErrors = new Set([
28 'getModifierState is not a function', // https://github.com/microsoft/monaco-editor/issues/4325
29]);
30
31export function showGlobalErrorMessage(msg) {
32 const pageContent = document.querySelector('.page-content');
33 if (!pageContent) return;
34
35 for (const filteredError of filteredErrors) {
36 if (msg.includes(filteredError)) return;
37 }
38
39 // compact the message to a data attribute to avoid too many duplicated messages
40 const msgCompact = msg.replace(/\W/g, '').trim();
41 let msgDiv = pageContent.querySelector(`.js-global-error[data-global-error-msg-compact="${msgCompact}"]`);
42 if (!msgDiv) {
43 const el = document.createElement('div');
44 el.innerHTML = `<div class="ui container negative message center aligned js-global-error tw-mt-[15px] tw-whitespace-pre-line"></div>`;
45 msgDiv = el.childNodes[0];
46 }
47 // merge duplicated messages into "the message (count)" format
48 const msgCount = Number(msgDiv.getAttribute(`data-global-error-msg-count`)) + 1;
49 msgDiv.setAttribute(`data-global-error-msg-compact`, msgCompact);
50 msgDiv.setAttribute(`data-global-error-msg-count`, msgCount.toString());
51 msgDiv.textContent = msg + (msgCount > 1 ? ` (${msgCount})` : '');
52 pageContent.prepend(msgDiv);
53}
54
55/**
56 * @param {ErrorEvent|PromiseRejectionEvent} event - Event
57 * @param {string} event.message - Only present on ErrorEvent
58 * @param {string} event.error - Only present on ErrorEvent
59 * @param {string} event.type - Only present on ErrorEvent
60 * @param {string} event.filename - Only present on ErrorEvent
61 * @param {number} event.lineno - Only present on ErrorEvent
62 * @param {number} event.colno - Only present on ErrorEvent
63 * @param {string} event.reason - Only present on PromiseRejectionEvent
64 * @param {number} event.promise - Only present on PromiseRejectionEvent
65 */
66function processWindowErrorEvent({error, reason, message, type, filename, lineno, colno}) {
67 const err = error ?? reason;
68 const {runModeIsProd} = window.config ?? {};
69
70 // `error` and `reason` are not guaranteed to be errors. If the value is falsy, it is likely a
71 // non-critical event from the browser. We log them but don't show them to users. Examples:
72 // - https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver#observation_errors
73 // - https://github.com/mozilla-mobile/firefox-ios/issues/10817
74 // - https://github.com/go-gitea/gitea/issues/20240
75 if (!err) {
76 if (message) console.error(new Error(message));
77 if (runModeIsProd) return;
78 }
79
80 // In production do not display errors that should be ignored.
81 if (runModeIsProd && shouldIgnoreError(err)) return;
82
83 let msg = err?.message ?? message;
84 if (lineno) msg += ` (${filename} @ ${lineno}:${colno})`;
85 const dot = msg.endsWith('.') ? '' : '.';
86 const renderedType = type === 'unhandledrejection' ? 'promise rejection' : type;
87 showGlobalErrorMessage(`JavaScript ${renderedType}: ${msg}${dot} Open browser console to see more details.`);
88}
89
90function initGlobalErrorHandler() {
91 if (window._globalHandlerErrors?._inited) {
92 showGlobalErrorMessage(`The global error handler has been initialized, do not initialize it again`);
93 return;
94 }
95 if (!window.config) {
96 showGlobalErrorMessage(`Gitea JavaScript code couldn't run correctly, please check your custom templates`);
97 }
98 // we added an event handler for window error at the very beginning of <script> of page head the
99 // handler calls `_globalHandlerErrors.push` (array method) to record all errors occur before
100 // this init then in this init, we can collect all error events and show them.
101 for (const e of window._globalHandlerErrors || []) {
102 processWindowErrorEvent(e);
103 }
104 // then, change _globalHandlerErrors to an object with push method, to process further error
105 // events directly
106 window._globalHandlerErrors = {_inited: true, push: (e) => processWindowErrorEvent(e)};
107}
108
109initGlobalErrorHandler();