Newer
Older
smart-home-server / webclient-vue / src / composables / useGlobalErrorHandler.js
@Eugene Sukhodolskiy Eugene Sukhodolskiy 15 hours ago 1 KB Add global error handling (Phase 2)
/**
 * Composable that wires up global error-catching surfaces.
 * Should be called once during app bootstrap (main.js).
 */
export function useGlobalErrorHandler(app) {
  /**
   * 1. Vue runtime errors — render, watcher, lifecycle hooks, event handlers.
   *    This does NOT catch errors inside async functions (those are promises).
   */
  app.config.errorHandler = (err, instance, info) => {
    const message = err?.message || String(err);
    console.error(`[Vue errorHandler] ${info}`, message, err);
    // In Phase 3 this is where we would push to a toast/notification service.
  };

  /**
   * 2. Unhandled promise rejections (fetch without catch, async function
   *    that throws and is not awaited, etc.)
   */
  window.addEventListener("unhandledrejection", (event) => {
    const reason = event.reason;
    const message = reason?.message || reason?.error?.message || String(reason);
    console.error("[Unhandled rejection]", message, reason);
    // Prevent the default browser console noise (redundant with our log).
    event.preventDefault();
  });

  /**
   * 3. Global synchronous JS errors (script parse errors, runtime throws
   *    outside of Vue, etc.)
   */
  window.addEventListener("error", (event) => {
    const error = event.error;
    const message = error?.message || event.message || "Unknown error";
    console.error(
      `[Global error] ${message}`,
      "at",
      event.filename,
      event.lineno,
      event.colno,
      error
    );
  });
}