Error Handling
error handling try-catch unhandled errors debugging serverless functionsCaught Errors
Section titled “Caught Errors”Use standard try/catch blocks to handle errors and return meaningful responses:
import type { Request, Response } from 'express'
export default (_: Request, res: Response) => { try { throw new Error('This is an error') } catch (error) { console.log(error) res.status(500).json({ error: error.message, }) }}The console.log(error) call ensures the error appears in your function logs, including the full stack trace. The client receives a structured JSON response.
Unhandled Errors
Section titled “Unhandled Errors”If an error is thrown without being caught, the function crashes and the client receives a generic error response:
import type { Request, Response } from 'express'
export default (_: Request, _res: Response) => { throw new Error('This is an unhandled error')}Unhandled errors are still captured in the logs with level ERROR, so you can diagnose them from the logs page.
Best Practices
Section titled “Best Practices”- Log before responding: Call
console.log()orconsole.error()before sending the response so the error is captured in logs regardless of client behavior. - Use the invocation ID: Include
req.invocationIdin log messages to correlate errors with specific requests. See Logging for details. - Return structured errors: Use a consistent error shape (e.g.,
{ error: string }) so clients can parse failures reliably. - Set appropriate status codes: Use
400for bad input,401/403for auth failures, and500for unexpected server errors.