Skip to content
Edge Functions

错误处理

Implement proper error responses and client-side handling to create reliable applications.

错误处理 #

🌐 Error handling

实现正确的错误响应和客户端处理有助于调试,并让你的函数在生产中更容易维护。

🌐 Implementing the right error responses and client-side handling helps with debugging and makes your functions much easier to maintain in production.

在你的 Edge Functions 中,返回正确的 HTTP 状态码和错误信息:

🌐 Within your Edge Functions, return proper HTTP status codes and error messages:

1
Deno.serve(async (req) => {
2
try {
3
// Your function logic here
4
const result = await processRequest(req)
5
return new Response(JSON.stringify(result), {
6
headers: { 'Content-Type': 'application/json' },
7
status: 200,
8
})
9
} catch (error) {
10
console.error('Function error:', error)
11
return new Response(JSON.stringify({ error: error.message }), {
12
headers: { 'Content-Type': 'application/json' },
13
status: 500,
14
})
15
}
16
})

函数错误的最佳实践:

  • 针对每种情况使用正确的 HTTP 状态码。用户输入错误时返回 400,找不到内容时返回 404,服务器错误时返回 500,等等。这有助于调试,也让客户端应用可以正确处理不同类型的错误。
  • 在响应正文中包含有用的错误信息
  • 将错误记录到控制台以便调试(可以在日志标签中看到)

客户端错误处理 #

🌐 Client-side error handling

在你的客户端代码中,Edge 函数可能会抛出三种类型的错误:

🌐 Within your client-side code, an Edge Function can throw three types of errors:

  • FunctionsHttpError: 你的函数执行了,但返回了一个错误(4xx/5xx 状态)
  • FunctionsRelayError:客户端与 Supabase 之间的网络问题
  • FunctionsFetchError:完全无法访问该功能
1
import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from '@supabase/supabase-js'
2
3
const { data, error } = await supabase.functions.invoke('hello', {
4
headers: { 'my-custom-header': 'my-custom-header-value' },
5
body: { foo: 'bar' },
6
})
7
8
if (error instanceof FunctionsHttpError) {
9
const errorMessage = await error.context.json()
10
console.log('Function returned an error', errorMessage)
11
} else if (error instanceof FunctionsRelayError) {
12
console.log('Relay error:', error.message)
13
} else if (error instanceof FunctionsFetchError) {
14
console.log('Fetch error:', error.message)
15
}

一定要妥善处理错误。悄无声息出错的函数很难调试,有明确错误信息的函数修复起来很快。

🌐 Make sure to handle the errors properly. Functions that fail silently are hard to debug, functions with clear error messages get fixed fast.


错误监控 #

🌐 Error monitoring

你可以在 Supabase 控制面板的日志标签页里看到生产错误日志。

🌐 You can see the production error logs in the Logs tab of your Supabase Dashboard.

Function invocations.

想了解更多关于日志记录的信息,可以看看这篇指南

🌐 For more information on Logging, check out this guide.