DEV Community

Drishti Saraf
Drishti Saraf

Posted on

2

Error Handling in Frontend Development

Error handling is a crucial part of frontend development—it ensures a smooth user experience and helps developers debug issues efficiently. Whether you're working with JavaScript, React, or any other frontend framework, handling errors properly can prevent unexpected crashes and frustrating user interactions.

404 not found

Common Types of Errors in Frontend Development

  • Syntax Errors – These happen when there's a mistake in your code structure, preventing it from running.

  • Runtime Errors – These occur while the code is executing, like trying to access an undefined variable.

  • Logical Errors – These don't crash your app, but they produce incorrect results, making debugging tricky.

  • Network Errors – When API calls fail due to connectivity issues, timeouts, or server errors.

  • User Input Errors – Happen when users enter invalid data, so proper validation is needed.

How to Handle Errors Effectively

  • Using Try-Catch for Handling Errors

A try-catch block is great for catching runtime errors without breaking the entire application.

try {
  let result = riskyOperation(); // A function that may throw an error
} catch (error) {
  console.error("Oops! Something went wrong:", error);
}
Enter fullscreen mode Exit fullscreen mode
  • Handling Errors in Promises

For asynchronous operations, handling errors properly prevents app crashes.

fetch("https://api.example.com/data")
  .then(response => response.json())
  .catch(error => console.error("Failed to fetch data:", error));
Enter fullscreen mode Exit fullscreen mode

With async/await:

async function fetchData() {
  try {
    let response = await fetch("https://api.example.com/data");
    let data = await response.json();
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Catching Global Errors

Using window.onerror or window.addEventListener("error", callback) helps capture unexpected errors globally.

window.onerror = function (message, source, lineno, colno, error) {
  console.error("Something went wrong:", message, " at ", source, ":", lineno);
};
Enter fullscreen mode Exit fullscreen mode

Handling unhandled promise rejections:

window.addEventListener("unhandledrejection", function (event) {
  console.error("Unhandled Promise Rejection:", event.reason);
});
Enter fullscreen mode Exit fullscreen mode
  • Handling Errors in React Applications

React provides error boundaries to catch component tree errors.

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error("Error caught by boundary:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>Oops! Something went wrong.</h1>;
    }
    return this.props.children;
  }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>
Enter fullscreen mode Exit fullscreen mode
  • Providing User-Friendly Feedback

Users should get clear messages when errors occur instead of vague alerts or crashes.

try {
  performAction();
} catch (error) {
  showToast("Something went wrong. Please try again.");
}
Enter fullscreen mode Exit fullscreen mode

Best Practices for Handling Errors

  1. Use Meaningful Error Messages – Avoid generic messages like "Something went wrong." Be specific.

  2. Log Errors Efficiently – Use tools like Sentry or LogRocket to capture and analyze errors.

  3. Fail Gracefully – Your app should remain functional even if an error occurs.

  4. Validate User Inputs – Prevent errors before they happen with proper validation.

  5. Test for Edge Cases – Use unit and integration tests to catch potential issues before deploying.

Final Thoughts

Error handling in frontend development is crucial for a smooth user experience. By implementing strategies like try-catch, promise handling, global error listeners, and React error boundaries, you can prevent app crashes and improve stability.

Do you have any go-to strategies for handling frontend errors? Share your thoughts in the comments!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)