STRESSUNFIT
STRESSUNFIT

Reputation: 41

Accessing File Name and Line Number in Production Errors with React Error Boundary

I'm implementing an error boundary in my React application to enhance error handling by capturing runtime errors and reporting them to a backend API for logging and analysis. The critical piece of information I need for each error is the original file name and line number where the error occurred. However, in production, our JavaScript code is minified, which complicates accessing these details due to the transformation and compression of the original source code.

Here's a snippet of my error boundary implementation for context:

import React, { useEffect, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import Navbar from "../../components/navbar/Navbar";

import styles from "./Admin.module.css";
import AdminSidePanel from "../../components/adminSidePanel/AdminSidePanel";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import ErrorFallback from "../../components/errorFallback/ErrorFallback";
import { useDispatch, useSelector } from "react-redux";
const Admin = () => {
  const dispatch = useDispatch();
  const location = useLocation();
  const navigate = useNavigate();

  function handleError(error, errorInfo) {
   //get line number and file name
  }

  return (
    <>
      <Navbar />
      <div className={styles.adminPageWrapper}>
        <div className={styles.sidePanelContainer}>
          <AdminSidePanel />
        </div>
        <div className={styles.contentPanelContainer}>
          <ErrorBoundary
            FallbackComponent={ErrorFallback}
            onError={handleError}
          >
            <Outlet />
          </ErrorBoundary>
        </div>
      </div>
    </>
  );
};

export default Admin;

Given the minification of code in production, direct access to the original file name and line number from the error stack is not possible. I understand that source maps are the key to solving this issue by mapping the minified code back to its original source, but i am not sure how exactly to implement this. i am using vite build tool.

Upvotes: 0

Views: 120

Answers (0)

Related Questions