The TypeScript error occurs because the error in the catch block is of type unknown, which is the correct type for caught errors in TypeScript (since TypeScript 4.0). This is a safety feature to prevent assuming the error is always an Error object.
Here are the best ways to handle this:
1. Type Guard (Recommended)
Use a type guard to check if the error is an instance of Error:
catch (error: unknown) {
console.error("Function error:", error);
// Type guard to check if it's an Error
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return new Response(
JSON.stringify({
error: "Internal server error.",
details: errorMessage,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 500,
}
);
}
2. Type Assertion (Less Safe)
If you're certain the error will always be an Error, you can use a type assertion:
catch (error: unknown) {
console.error("Function error:", error);
return new Response(
JSON.stringify({
error: "Internal server error.",
details: (error as Error).message,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 500,
}
);
}
3. Error Handling Utility Function
For better reusability, create a utility function:
function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === 'string') return error;
return 'Unknown error';
}
// Usage:
catch (error: unknown) {
console.error("Function error:", error);
return new Response(
JSON.stringify({
error: "Internal server error.",
details: getErrorMessage(error),
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
status: 500,
}
);
}
Best Practice Recommendation:
The first approach (type guard) is the most type-safe and recommended way. It properly handles all possible error types while maintaining type safety. The utility function approach is also excellent if you need to handle errors in multiple places.