The error below is thrown on line 13 of App.tsx
, but the stack trace says line 35. How can I get the React error boundary to show line numbers corresponding to my actual files, instead of these transpiled ones?
App.tsx
import ErrorBoundary from "./ErrorBoundary";
function App() {
return (
<div>
<ErrorBoundary>
<Inner />
</ErrorBoundary>
</div>
);
}
function Inner() {
throw new Error("Error: I crashed!");
return "App";
}
export default App;
ErrorBoundary.tsx
import React from "react";
interface Props {
children: React.ReactNode;
}
interface State {
error: any;
errorInfo: any;
}
const defaultState: State = {
error: null,
errorInfo: null,
};
// https://legacy.reactjs.org/docs/error-boundaries.html
// https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary
class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = defaultState;
}
componentDidCatch(error: Error, errorInfo: { componentStack: string }) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Error
console.log("ErrorBoundary", { error, errorInfo });
console.log(error instanceof Error);
this.setState({
error: error,
errorInfo: errorInfo,
});
}
render() {
const fallback = (
<div>
<section>
<h3>An error occured.</h3>
<h4>error.message</h4>
<pre>{this.state?.error?.message}</pre>
<h4>error.stack</h4>
<pre>{this.state?.error?.stack}</pre>
<h4>errorInfo.componentStack</h4>
<pre>{this.state?.errorInfo?.componentStack}</pre>
</section>
<button
onClick={() => {
this.setState(defaultState);
}}
>
Try again
</button>
</div>
);
if (this.state?.error?.message) {
return fallback;
}
return this.props.children;
}
}
export default ErrorBoundary;