[ Error handling ] How to know the code error line number?

In CEP we had the err.line property for the err in a try / catch block:

try {
// SOME CODE
 } catch(err) { 
console.log(err.line);
}

So it was easy to track the line code where the error was happening, however with UXP there’s no err.line or at least I haven’t find a way, what is the solution for this or an alternative?

I’ve tried err.stack but sometimes it doesn’t throws the error line.

Thanks!

Use console.trace(err) instead.

5 Likes

Thanks for the answer it works! Now If I want to “alert” this err doesn’t give me a way to trace the line error. Do you have any suggestions?

You can get the stack trace as a string with err.stack.
There’s no method to return just the line reference afaik, but you could do something like this to mutate the string to an array and then alert the relevant element.

const formatStackTrace = (stack) => {
  return stack.split("\n").map(line => line.trim());
};

// ...
catch (err) {
  const stackTraceArr = formatStackTrace(err.stack)
  alert(stackTraceArr[1])
}
1 Like

It’s worth considering what and why you’re erroring. You mentioned using Alerts. Alerts are generally for users, and users don’t care about exceptions — they want human formatted error messages, which you write yourself, that are specific to how they should respond, not the code that caused them.

If you’re just trying to do local debugging, use console.error(yourError). The chromium console will print most of the stack trace for you without any additional work, and if you’ve got sourcemaps hooked up, they’ll link right to the source.

And for remote debugging, I strongly recommend using something like https://sentry.io/. That way you get notified of your production errors and they point specifically at the code that caused the issues. Setting up Sentry is one of the first things I do on every project and write code in a way that specifically accounts for errors and sends them to Sentry with the relevant context.

2 Likes