Handling async and mouse event errors using context #64083
-
SummaryI'm well aware that ErrorBoundary in React does not handle errors from async and mouse events. However, I'm looking for a way to centralise the logic for handling those types of errors by having the state managed by some sort of context and then having that error state propagated to the error boundary. I have the following "use client";
import { createContext, useContext, useState } from "react";
import type { ReactNode } from "react";
interface ErrorContextType {
error: Error | null;
setErrorHandler: (error: Error) => void;
clearErrorHandler: () => void;
}
const ErrorContext = createContext<ErrorContextType | undefined>(undefined);
export const useError = (): ErrorContextType => {
const context = useContext(ErrorContext);
if (!context) {
throw new Error("useError must be used within a ErrorProvider");
}
return context;
};
export const ErrorProvider = ({ children }: { children: ReactNode }) => {
const [error, setError] = useState<Error | null>(null);
const setErrorHandler = (error: Error) => setError(error);
const clearErrorHandler = () => setError(null);
return (
<ErrorContext.Provider
value={{ error, setErrorHandler, clearErrorHandler }}
>
{children}
</ErrorContext.Provider>
);
}; And then in the app folder, I have a new component called export default function Providers({ children }: { children: any }) {
return <ErrorProvider>{children}</ErrorProvider>;
} And finally I have this component injected into the root layout. I have an Now within the child, I use the Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi,
But you can make it be aware of them... Kent C Dodds goes in depth about it here: https://kentcdodds.com/blog/use-react-error-boundary-to-handle-errors-in-react#handle-all-errors And although he is using the Anyway, you can see how they implemented their solution here: https://github.com/bvaughn/react-error-boundary/blob/master/src/useErrorBoundary.ts |
Beta Was this translation helpful? Give feedback.
Hi,
But you can make it be aware of them...
Kent C Dodds goes in depth about it here: https://kentcdodds.com/blog/use-react-error-boundary-to-handle-errors-in-react#handle-all-errors
And although he is using the
react-error-boundary
library, you could still do that yourself. Though I'd recommend using that library, because it develops the Error Boundary API very well.Anyway, you can see how they implemented their solution here: https://github.com/bvaughn/react-error-boundary/blob/master/src/useErrorBoundary.ts