1

I am using create-react-app to build my application and new relic's noticeError() to log errors.

Below, you can see an example of how I log errors:

  var err = new Error('Report caught error to New Relic');
  
  // exported from logger.ts
  logError(err, {
    hint:
      'Check the validateToken() function. The JWT token might have expired',
    filePath: 'src/routes/Routes.tsx',
  });

logger.ts

import { getLocalStorage } from '../utils/localStorageHandler';
import LOCALSTORAGE_KEYS from '../constants/localStorageKeys';
import { CandidatePersonalDetail } from '../graphql/declarations';

interface Attributes {
  errorType: string;
  mobile?: string;
  userID?: number;
  role?: string;
  name?: string;
}

// Define and export your error types from here
export const ERROR_TYPES = {
  API_ERROR: 'API_ERROR',
};

export const logError = (
  err: any,
  customAttributes?: { [key: string]: string | number },
  callback?: () => void,
): void => {
  const attributes: Attributes = {
    errorType: ERROR_TYPES.API_ERROR,
    ...customAttributes,
  };

  const personalDetails:
    | CandidatePersonalDetail['candidate']
    | null = getLocalStorage(LOCALSTORAGE_KEYS.USER_PERSONAL_DETAILS);

  // If personal details exist in local storage
  if (personalDetails && Object.keys(personalDetails).length) {
    if (personalDetails.mobile) {
      attributes.mobile = personalDetails.mobile;
    }

    if ((personalDetails as any).role) {
      attributes.userID = personalDetails.id;
      attributes.name = `${personalDetails.firstName} ${personalDetails.lastName}`;
      attributes.role = (personalDetails as any).role;
    }
  }

  (window as any).newrelic.noticeError(err, attributes);

  if (callback) {
    callback();
  }
};

I am manually adding the file path to help the developers as much as I can to debug. Is it possible to automate this by accessing the file path whenever logError() function is called so that I can pass it as a custom attribute to new relic? I am ok with absolute or relative paths. Thanks in anticipation.

shet_tayyy
  • 5,366
  • 11
  • 44
  • 82
  • see: [Stack traces](https://developer.mozilla.org/en-US/docs/Web/API/Console#stack_traces)? and [Print current stack trace in JavaScript](https://stackoverflow.com/questions/43236925/print-current-stack-trace-in-javascript) or the non-standard [Error#stack](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack) – pilchard Jun 05 '21 at 09:49

0 Answers0