In my app if any errors occur inside components I need to redirect to a top-level error page. Suppose I'm using React-Router and have the following route defined,
<Switch>
..
<Route path="/error">
<Error />
</Route>
Suppose in some down-level component something fails. I get an error object with .message and .stack. I need my Error component to display the error details after a Router <Redirect />.
const [error, setError] = useState({});
const someComponentFetch = async () => {
const url = '/myapp/data';
try {
//...
}
catch (error) {
setError(error);
}
}
if (error.message) {
return <Redirect to="/error" />
}
return (..);
Error component expects a props object:
export default function Error(props) {
return (
<div>
Error Occurred:
<div>
Message: {props.error.message} <br/>
Stack: {props.error.stack}
</div>
</div>
);
}
Error: TypeError: props.error is undefined . So <Redirect> doesn't pass my properties. What's the best way to have a top-level Error page with error details? If I were to check error ? .. in every component it wouldn't be a top-level page, it would be a message inside each component.