Error Handling Best Practices
Proper error handling is crucial for building robust applications that provide good user experiences.
Error Types
Understanding different error types helps you handle them appropriately.
Syntax Errors
Caught at compile time or parse time:
const message = "Hello World"; // Fixed syntax
console.log(message);
Runtime Errors
Occur during execution:
function parseJSON(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch (error) {
if (error instanceof SyntaxError) {
console.error('Invalid JSON:', error.message);
return null;
}
throw error;
}
}
Error Boundaries in React
Important: Error boundaries only catch errors in class components. Use libraries like react-error-boundary for functional components.
import { ErrorBoundary } from 'react-error-boundary';
function ErrorFallback({ error, resetErrorBoundary }: any) {
return (
<div role="alert">
<h2>Something went wrong:</h2>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function App() {
return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
<MyComponent />
</ErrorBoundary>
);
}
Best Practice: Always provide meaningful error messages and recovery options for users.