Implementing Error Handling Strategies in JavaScript Applications

Best practices for handling errors gracefully in JavaScript to improve application robustness and user experience.

0 likes
9 views

Rule Content

{
  "title": "Implementing Error Handling Strategies in JavaScript Applications",
  "description": "Best practices for handling errors gracefully in JavaScript to improve application robustness and user experience.",
  "category": "JavaScript Cursor Rules",
  "rules": [
    {
      "id": "js-error-handling-try-catch",
      "description": "Use try-catch blocks to handle exceptions in synchronous code.",
      "example": {
        "before": "const data = JSON.parse(jsonString);",
        "after": "try {\n  const data = JSON.parse(jsonString);\n} catch (error) {\n  console.error('Failed to parse JSON:', error.message);\n}"
      }
    },
    {
      "id": "js-error-handling-promises",
      "description": "Handle errors in Promises using the .catch() method.",
      "example": {
        "before": "fetch(url).then(response => response.json()).then(data => console.log(data));",
        "after": "fetch(url)\n  .then(response => response.json())\n  .then(data => console.log(data))\n  .catch(error => console.error('Fetch error:', error.message));"
      }
    },
    {
      "id": "js-error-handling-async-await",
      "description": "Use try-catch blocks with async/await for asynchronous code.",
      "example": {
        "before": "const response = await fetch(url);\nconst data = await response.json();",
        "after": "try {\n  const response = await fetch(url);\n  const data = await response.json();\n} catch (error) {\n  console.error('Fetch error:', error.message);\n}"
      }
    },
    {
      "id": "js-error-handling-custom-errors",
      "description": "Create custom error classes for more specific error handling.",
      "example": {
        "before": "throw new Error('Invalid input');",
        "after": "class ValidationError extends Error {\n  constructor(message) {\n    super(message);\n    this.name = 'ValidationError';\n  }\n}\n\nthrow new ValidationError('Invalid input');"
      }
    },
    {
      "id": "js-error-handling-global",
      "description": "Implement global error handlers to catch unhandled errors and promise rejections.",
      "example": {
        "before": "// No global error handling",
        "after": "window.addEventListener('error', (event) => {\n  console.error('Global error:', event.message);\n});\n\nwindow.addEventListener('unhandledrejection', (event) => {\n  console.error('Unhandled promise rejection:', event.reason);\n});"
      }
    },
    {
      "id": "js-error-handling-logging",
      "description": "Log errors appropriately for monitoring and debugging.",
      "example": {
        "before": "console.error('An error occurred');",
        "after": "function logError(error) {\n  console.error('Error:', error.message);\n  // Optionally, send error details to a logging service\n}\n\ntry {\n  // Code that may throw an error\n} catch (error) {\n  logError(error);\n}"
      }
    },
    {
      "id": "js-error-handling-meaningful-messages",
      "description": "Provide meaningful error messages to aid in debugging.",
      "example": {
        "before": "throw new Error('Something went wrong');",
        "after": "throw new Error('Failed to fetch user data due to network issues');"
      }
    },
    {
      "id": "js-error-handling-fallback",
      "description": "Implement fallback strategies to maintain functionality when an error occurs.",
      "example": {
        "before": "const data = fetchData();",
        "after": "try {\n  const data = fetchData();\n} catch (error) {\n  console.error('Fetch error:', error.message);\n  const data = getCachedData(); // Fallback to cached data\n}"
      }
    }
  ]
}