Skip to content

Commit

Permalink
fix: gracefully handle errors when setting headers (#5411)
Browse files Browse the repository at this point in the history
* fix: gracefully handle errors when setting headers

* feat: show error page
  • Loading branch information
eduardoboucas committed Jan 20, 2023
1 parent 2aa9341 commit 734c23c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 8 deletions.
2 changes: 1 addition & 1 deletion src/lib/functions/server.mjs
Expand Up @@ -168,7 +168,7 @@ export const createHandler = function (options) {
return
}

handleSynchronousFunction(error, result, request, response)
handleSynchronousFunction({ error, functionName: func.name, result, request, response })
}
}
}
Expand Down
35 changes: 28 additions & 7 deletions src/lib/functions/synchronous.mjs
@@ -1,7 +1,7 @@
// @ts-check
import { Buffer } from 'buffer'

import { NETLIFYDEVERR } from '../../utils/command-helpers.mjs'
import { chalk, log, NETLIFYDEVERR } from '../../utils/command-helpers.mjs'
import renderErrorTemplate from '../render-error-template.mjs'

import { detectAwsSdkError } from './utils.mjs'
Expand All @@ -16,27 +16,48 @@ const addHeaders = (headers, response) => {
})
}

export const handleSynchronousFunction = function (err, result, request, response) {
if (err) {
return handleErr(err, request, response)
export const handleSynchronousFunction = function ({
error: invocationError,
functionName,
request,
response,
result,
}) {
if (invocationError) {
return handleErr(invocationError, request, response)
}

const { error } = validateLambdaResponse(result)
if (error) {
console.log(`${NETLIFYDEVERR} ${error}`)
log(`${NETLIFYDEVERR} ${error}`)
return handleErr(error, request, response)
}

response.statusCode = result.statusCode
addHeaders(result.headers, response)
addHeaders(result.multiValueHeaders, response)

try {
addHeaders(result.headers, response)
addHeaders(result.multiValueHeaders, response)
} catch (headersError) {
formatError(headersError)

log(`${NETLIFYDEVERR} Failed to set header in function ${chalk.yellow(functionName)}: ${headersError.message}`)

return handleErr(headersError, request, response)
}

if (result.body) {
response.write(result.isBase64Encoded ? Buffer.from(result.body, 'base64') : result.body)
}
response.end()
}

const formatError = (err) => {
err.errorType = err.code
err.errorMessage = err.message
err.stackTrace = err.trace
}

const formatLambdaLocalError = (err, acceptsHtml) =>
acceptsHtml
? JSON.stringify({
Expand Down

1 comment on commit 734c23c

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📊 Benchmark results

  • Package size: 267 MB

Please sign in to comment.