Handling of Nonexistent Paths
Even though we prevent navigation to undefined paths with the power of types, a user may visit arbitrary paths by directly entering a path to their browser's address bar. Therefore, our app has to handle these cases, typically by showing a “not found” page, or by redirecting to the top page.
If an undefined path is encountered, useRoutes
throws a LocationNotFoundError
. To catch the error, you can use an error boundary. Rocon exports an isLocationNotFoundError
function to check whether a catched error is a LocationNotFoundError
. Utilizing this function, a typical error boundary for Rocon looks like:
import { isLocationNotFoundError } from "rocon/react";
type State = {
notFound: boolean;
};
export class ErrorBoundary extends React.Component {
state: State = {
notFound: false,
};
componentDidCatch(error: unknown) {
if (isLocationNotFoundError(error)) {
this.setState({
notFound: true,
});
} else {
throw error;
}
}
render() {
if (this.state.notFound) {
return <NotFoundPage />;
} else {
return <Fragment>{this.props.children}</Fragment>;
}
}
}