Error handling
Rakkas provides an ErrorBoundary
component for handling errors that occur while rendering or fetching data. It is simply a repackaging of the ErrorBoundary
component from the react-error-boundary
package.
It's used like this:
import { ErrorBoundary } from "rakkasjs";
import { ComponentThatMayThrow } from "./ComponentThatMayThrow";
export default function MyComponent() {
return (
<ErrorBoundary
fallbackRender={({ error, resetErrorBoundary }) => (
<div>
<h1>An error has occurred</h1>
<pre>{error.message}</pre>
<button
onClick={() => {
resetErrorBoundary();
}}
>
Try again
</button>
</div>
)}
>
<ComponentThatMayThrow />
</ErrorBoundary>
);
}
You should be aware that React doesn't render error boundaries during SSR. If an error occurs during SSR, React will simply retry to render the page on the client. For this reason, it's probably best not to use exceptions for error handling:
// Don't do this if tryToFetchSomeData can throw:
// useQuery(() => tryToFetchSomeData());
// Do this instead:
const { data: result } = useQuery(() => {
try {
const data = tryToFetchSomeData();
return { data };
} catch (error) {
return { error: error.message };
}
});
if ("error" in result) {
// Handle error
} else {
// Use data
}