I’ve recently been doing a lot of Error Handling in my full-time job as a software developer. Usually, developers pay attention to error handling at the intermediate-senior level since before that, they don’t bother to control how their app will work unexpectedly.
Error handling is a crucial part of modern JavaScript and React development, ensuring your apps don’t break unexpectedly. One of the most popular and straightforward ways to handle errors is by using try...catch
.
๐ How It Works
The try
block contains the code you want to execute. If an error occurs, the catch
block handles it gracefully, preventing your app from crashing.
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
๐ In React Components
React error handling often combines try...catch
with hooks like useEffect
or in event handlers:
import React, { useState, useEffect } from 'react';
function DataFetcher() {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (err) {
setError(err.message);
}
};
fetchData();
}, []);
return (
<div>
{error ? <p>Error: {error}</p> : <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
โก Key Benefits of try...catch
- Graceful Error Recovery: Prevent app crashes by catching unexpected errors.
- Debugging Insights: Log errors for analysis.
- User-Friendly Experience: Show fallback UI or error messages instead of blank screens.
๐ Pro Tip (Extra)
Use try...catch
selectively and combine it with tools like Error Boundaries in React for better handling of rendering errors. But don’t forget that ErrorBoundary doesn’t catch async functions, for example, API calls or event handlers:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error("ErrorBoundary caught an error", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Leave a Reply