惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Jina AI
Jina AI
博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
美团技术团队
腾讯CDC
博客园 - Franky
MyScale Blog
MyScale Blog
人人都是产品经理
人人都是产品经理
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
aimingoo的专栏
aimingoo的专栏
博客园_首页
V
V2EX
Martin Fowler
Martin Fowler
T
The Blog of Author Tim Ferriss

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Supabase Edge Function Error Handling — Retries, Logging,...
kanta13jp1 · 2026-04-29 · via DEV Community

kanta13jp1

Supabase Edge Function Error Handling — Retries, Logging, and Idempotency

Design patterns to prevent errors from being swallowed silently in production EFs.

Basics: Return Structured Errors

// supabase/functions/_shared/error.ts
export class AppError extends Error {
  constructor(
    message: string,
    public readonly code: string,
    public readonly status: number = 500,
  ) {
    super(message);
  }
}

export function errorResponse(error: unknown): Response {
  if (error instanceof AppError) {
    return new Response(
      JSON.stringify({ error: error.message, code: error.code }),
      { status: error.status, headers: { 'Content-Type': 'application/json' } },
    );
  }
  console.error('Unexpected error:', error);
  return new Response(
    JSON.stringify({ error: 'Internal server error', code: 'INTERNAL' }),
    { status: 500, headers: { 'Content-Type': 'application/json' } },
  );
}

Enter fullscreen mode Exit fullscreen mode

Fetch with Retry

async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3,
): Promise<Response> {
  let lastError: Error | undefined;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const res = await fetch(url, options);
      if (res.status === 429) {
        // Rate limit: exponential backoff
        const wait = Math.pow(2, attempt) * 1000;
        await new Promise(r => setTimeout(r, wait));
        continue;
      }
      if (!res.ok && res.status >= 500) {
        throw new Error(`HTTP ${res.status}`);
      }
      return res;
    } catch (e) {
      lastError = e as Error;
      if (attempt < maxRetries) {
        await new Promise(r => setTimeout(r, attempt * 500));
      }
    }
  }
  throw lastError ?? new Error('Max retries exceeded');
}

Enter fullscreen mode Exit fullscreen mode

Structured Logging

// Common log format across all EFs
function log(level: 'info' | 'warn' | 'error', message: string, meta?: object) {
  console.log(JSON.stringify({
    level,
    message,
    timestamp: new Date().toISOString(),
    function: Deno.env.get('FUNCTION_NAME') ?? 'unknown',
    ...meta,
  }));
}

// Usage
log('info', 'Processing webhook', { event_type: event.type });
log('error', 'Stripe API failed', { attempt: 3, status: 500 });

Enter fullscreen mode Exit fullscreen mode

Idempotent Webhook Processing

// Prevent double-processing the same event
const { data: processed } = await supabase
  .from('processed_webhooks')
  .select('id')
  .eq('event_id', event.id)
  .maybeSingle();

if (processed) {
  return new Response('ok'); // silently ignore duplicates
}

// Record after processing
await supabase.from('processed_webhooks').insert({
  event_id: event.id,
  processed_at: new Date().toISOString(),
});

Enter fullscreen mode Exit fullscreen mode

Summary

Error responses  → AppError + errorResponse (structured JSON)
Retries          → exponential backoff (for 429 and 5xx)
Logging          → structured JSON logs (searchable in Supabase Dashboard)
Idempotency      → processed_webhooks table prevents double-processing

Enter fullscreen mode Exit fullscreen mode

Design EFs to be "safe to fail" by default.