Skip to content

Commit

Permalink
Merge pull request #1257 from danskernesdigitalebibliotek/feature/DDF…
Browse files Browse the repository at this point in the history
…LSBP-569-logging-i-frontend

Forward exceptions to window.onerror  [DDFLSBP-569]
  • Loading branch information
clausbruun authored Jun 27, 2024
2 parents 267fa20 + 7e70f4b commit 2356bba
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/core/mount.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Store from "../components/store";
import { persistor, store } from "./store";
import ErrorBoundaryAlert from "../components/error-boundary-alert/ErrorBoundaryAlert";
import { closeLastModal } from "./modal.slice";
import forwardError from "./utils/forwardError";

/**
* We look for containers and corresponding applications.
Expand Down Expand Up @@ -37,6 +38,8 @@ function mount(context) {
// Logging should be acceptable in an error handler.
// eslint-disable-next-line no-console
console.error(error, info);

forwardError(error, info);
}
}),
{
Expand Down
33 changes: 33 additions & 0 deletions src/core/utils/extractErrorDetails.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Extracts error details from a stack trace.
*
* @param {string} stack - The stack trace.
* @returns {Object} An object containing filename, lineNumber, and column.
*/
const extractErrorDetails = (stack) => {
const stackLines = (stack || "").split("\n");
const match = stackLines
.map((line) => {
// Extract filename, lineNumber, and column from a string formatted like "filename:line:column"
const parts = line.match(/(?:\()?(.*?):(\d+):(\d+)(?:\))?/);
if (parts) {
const [, filename, lineNumber, column] = parts;
return {
filename,
lineNumber,
column
};
}
return null;
})
.find((m) => m);
return (
match || {
filename: "unknown",
lineNumber: "0",
column: "0"
}
);
};

export default extractErrorDetails;
29 changes: 29 additions & 0 deletions src/core/utils/forwardError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import extractErrorDetails from "./extractErrorDetails";

/**
* Forwards an error to the window.onerror handler.
*
* @param {Error} error - The error object.
* @param {Object} info - Additional info, including component stack trace.
*/
const forwardError = (error, info) => {
const { filename, lineNumber, column } = extractErrorDetails(
info.componentStack
);

// Call window.onerror to send the error to the error logging system.
if (window.onerror) {
window.onerror(
`${error.name}: ${error.message}`,
filename,
lineNumber,
column,
{
...info,
stack: info.componentStack
}
);
}
};

export default forwardError;

0 comments on commit 2356bba

Please sign in to comment.