Skip to content

Edge Function 500 error response

Last edited: 8/12/2026

Edge 函数返回 500 有两种可能情况。

🌐 A 500 from an Edge Function means one of two things.

  • 这个函数遇到了一个未处理的 JavaScript 错误
  • 你的代码故意返回了一个500响应

快速分诊 #

🌐 Quick triage

如果你收到了下面的消息,那就去看一下 JavaScript 错误 部分:

🌐 If you received back the below message, then go to the JavaScript failure section:

1
Internal Server Error

如果正文包含自定义消息,或者根本没有内容,设置好时间范围后,在 Log Explorer 中运行以下查询:

1
select
2
console_logs.event_message,
3
cast(invocation_events.timestamp as datetime) as timestamp,
4
invocation_events.function_name
5
from
6
function_logs as console_logs
7
left join UNNEST(console_logs.metadata) as metadata on true
8
left join (
9
select
10
timestamp,
11
em.execution_id,
12
res.status_code,
13
req.pathname as function_name
14
from
15
function_edge_logs
16
left join UNNEST(metadata) as em on true
17
left join UNNEST(em.request) as req on true
18
left join UNNEST(em.response) as res on true
19
) as invocation_events
20
on metadata.execution_id = invocation_events.execution_id
21
where
22
invocation_events.status_code = 500
23
and metadata.level = 'error'
24
and metadata.event_type in ('Log', 'UncaughtException')
25
and console_logs.event_message like '%Error:%file:///%'
26
order by invocation_events.function_name, invocation_events.timestamp
27
limit 50;

根据输出,去相关部分:

🌐 Based on the output, go to the relevant section:

你的自定义响应返回了 500 #

🌐 Your custom response returned a 500

在你的函数逻辑的某个地方,你自己返回了一个 500 响应:

🌐 Somewhere in your function logic, you are returning a 500 response yourself:

示例: #

🌐 Example:

1
return new Response(JSON.stringify(data), {
2
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
3
status: 500, // <-- you set this
4
})

修复: #

🌐 Fix:

  1. 在你的函数代码中搜索 status: 500(或 status: "500")
  2. 追踪触发它的条件。检查可能向函数返回 500 响应的任何第三方 API 响应。
  3. 在代码返回之前添加一个带自定义 console.error() 消息的 try/catch 块,这样未来出现问题时会留下更清晰的痕迹。

参见:Edge Functions 中的错误处理

🌐 See: Error handling in Edge Functions

JavaScript 失败 #

🌐 JavaScript failure

在执行过程中出现了一个未处理的 JavaScript 错误

🌐 An unhandled JavaScript Error emerged during execution.

该函数的日志将生成带有错误类型的 event_message。它可能看起来像这样:

🌐 The function's log will produce an event_message with the error type. It may look like:

1
TypeError: Cannot read properties of undefined (reading 'some_func')
2
at Object.handler (file:///var/tmp/sb-compile-edge-runtime/source/index.ts:15:26)
3
at eventLoopTick (ext:core/01_core.js:175:7)
4
at async mapped (ext:runtime/http.js:246:20)

第一行会告诉你错误类型和信息。堆栈跟踪指向具体的文件和行号。

🌐 The first line tells you the error type and message. The stack trace points to the file and line number.

Mozilla 基金会记录了所有错误对象及其含义:

🌐 The Mozilla Foundation documents all error objects and what they mean:

不过,你也可以看下面的示例案例,了解可能的原因。

🌐 However, you can also review the below example cases for an idea of possible causes.

示例案例 #

🌐 Example cases

类型错误:未定义的变量 #

🌐 TypeError: Undefined variables

当任何 JavaScript 数据类型被误用时,就会发生 TypeError。例如,尝试像执行函数一样执行一个数字就会导致这个错误:

🌐 A TypeError occurs when any JavaScript datatype is misused. For instance, trying to execute a number as if it were a function would cause the error:

1
const some_num = 5
2
3
some_num() // TypeError: some_num is not a function

当处理来自外部 API 返回的对象时,这个问题经常出现。有人可能会以为响应有某种固定的结构,但如果值是 nullundefined,在没有检查的情况下使用它可能会导致 TypeError

🌐 This issue often appears when working with returned objects from external APIs. One may assume a response has a certain shape, but if the value is null or undefined, using it without checking can lead to a TypeError.

1
const data = await req.json() // returns undefined if request body is empty
2
data.some_obj.some_val // TypeError: Cannot read properties of undefined

解决方法 1:在使用可能未知的值之前进行类型检查: #

🌐 Fix 1: Type-check before using potentially unknown values:

1
const { user_submission } = await req.json()
2
3
// checking value for appropriate datatype
4
if (typeof user_submission === 'undefined') {
5
return new Response(JSON.stringify({ message: 'Submission is empty. Please try again.' }), {
6
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
7
status: 400,
8
})
9
}
10
11
// rest of code ...

解决方法 2:用 try/catch 封装有问题的代码: #

🌐 Fix 2: Wrap problematic code in try/catch:

可以使用一个 try/catch/finally 块来处理这些错误:

🌐 One could use a try/catch/finally block to handle these errors:

1
try {
2
some_obj.some_func(); // TypeError: Cannot read properties of undefined
3
...
4
}
5
catch(err) {
6
// customize the error message
7
console.error('return object was misformatted:', err)
8
}
9
finally {
10
// add a custom error response for easier debugging
11
return new Response(JSON.stringify(
12
{ message: 'Could not parse return object' }),
13
{
14
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
15
status: 500 // opt to customize the status code to better fit the situation
16
}
17
)
18
}

引用错误:Var 未定义 #

🌐 ReferenceError: Var is not defined

ReferenceError 发生在尝试引用代码作用域中不存在的变量时。通常是由于拼写错误或缺少导入导致的。

🌐 A ReferenceError occurs when one tries to reference a variable that does not exist in the code's scope. Often times caused by a typo or missing import.

例如,如果有人在变量定义之前尝试访问它,他们会遇到这个错误:

🌐 For instance, if one tries to access a variable before it is defined, they will encounter the error:

1
let a = some_uninitialized_var // ReferenceError: some_uninitialized_var is not defined...

修复: #

🌐 Fix:

  • 检查错误信息中的变量名与代码是否一致,确保没有拼写错误
  • 确保在使用变量之前先声明它
  • 如果是从包里来的,确认导入存在且导出名称正确
  • 如果错误涉及到 JavaScript 内部内容,确保它与 Supabase 运行环境兼容。如果不兼容,可以考虑重构或者更新库的版本

自定义错误 #

🌐 Custom errors

你在代码的某个地方明确抛出了一个错误,或者是第三方包抛的:

🌐 You explicitly threw an error somewhere in your code, or a third-party package did:

1
throw new Error('custom, unhandled error')

或者,在try/catch 块中,你可能已经增强了标准错误信息:

🌐 Alternatively, in a try/catch blocks, you may have augmented the standard error message:

1
try {
2
// induce reference error
3
const a = unitialized_var // ReferenceError...
4
} catch (error) {
5
console.error('custom error message...', error) // modifying the original error message
6
}

当你自定义错误响应时,重要的是定义一个合适的新消息。将错误时返回的默认 500 代码改成一个更能反映实际情况的值,也可能是值得的,这样将来调试会更容易:

🌐 When you customize the error response, it's important to define an appropriate new message. It may also be worthwhile changing the default 500 code returned during errors to a value more reflective of the situation for easier debugging in the future:

1
...
2
catch (error) {
3
console.error('custom error message...', error) // modifying the original error message
4
return new Response(JSON.stringify(
5
{ message: 'Permissions error, please sign in' }),
6
{
7
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
8
status: 401 // customizing the status code
9
}
10
)
11
}

语法错误:特殊情况 - CORS 违规 #

🌐 SyntaxError: Special case - CORS violation

当违反 Deno 的语法规则时,例如没有关闭括号,就会发生 SyntaxError 错误:

🌐 A SyntaxError error occurs when Deno's grammatical rules are violated, such as failing to close a parenthesis:

1
console.log('unclosed' ; // Uncaught SyntaxError: missing ) after argument list

在大多数情况下,语法错误可以通过去掉一个打字错误来修复。有一个特殊情况很常见,值得举个例子说明:CORS 违规。

🌐 In most cases, syntax violations can be fixed by removing a typo. There is a special case that is common enough that it is worth providing an example over: CORS violations.

当你从浏览器打电话时,比如 FireFox 或 Chrome,网站会在发送实际数据前先发一个 OPTIONS 请求。这是一种安全机制,用来防止 跨站请求伪造攻击。要满足这个请求,你需要有一个 CORS 处理器

🌐 When making calls from a browser, such as FireFox or Chrome, the site will make an OPTIONS request before sending over the actual payload. This is a security mechanism done to prevent Cross-Site-Request-Forgery attacks. To satisfy the request, you need to have a CORS handler in place:

1
const corsHeaders = {
2
'Access-Control-Allow-Origin': '*',
3
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
4
}
5
6
Deno.serve(async (req) => {
7
// CORS handler: manages OPTIONS request
8
if (req.method === 'OPTIONS') {
9
return new Response('ok', { headers: corsHeaders })
10
}
11
})

没有 OPTIONS 处理器,浏览器发出的请求会被误解,从而导致 Unexpected end of JSON input 错误日志。

🌐 Without the OPTIONS handler, requests from the browser will be misinterpreted, resulting in an Unexpected end of JSON input error log.

1
SyntaxError: Unexpected end of JSON input
2
at parse (<anonymous>)
3
at packageData (ext:deno_fetch/22_body.js:408:14)
4
at consumeBody (ext:deno_fetch/22_body.js:261:12)
5
at eventLoopTick (ext:core/01_core.js:175:7)
6
at async Object.handler (file:///var/tmp/sb-compile-edge-runtime/source/index.ts:5:20)at async mapped (ext:runtime/http.js:246:20)

解决方法是按照我们的指南添加CORS支持

🌐 The solution is to follow our guide on adding CORS support.

同样重要的是要注意,如果在满足 CORS 检查之前发生任何错误,浏览器可能会错误地报告 CORS 是请求失败的原因:

🌐 It is also important to note that if any error occurs before the CORS check can be satisfied, the browser may falsely report CORS as the reason a request failed:

1
// returns before the CORS check can be satisfied
2
return
3
4
if (req.method === 'OPTIONS') {
5
return new Response('ok', { headers: corsHeaders })
6
}

所以,当遇到这些错误时,仍然重要的是检查日志或者在浏览器之外运行请求,以确保它是主要原因,而不是更大问题的副作用。

🌐 So, when encountering these errors, it is still important to check the logs or run the request outside the browser to make sure it is the primary factor and not a side-effect of a larger issue.

还卡住吗? #

🌐 Still stuck?