Global error handler for Serverless Typescript using decorators

Kıvanç Bilen
AWS Tip
Published in
1 min readJul 21, 2022

--

When you start a new project with serverless framework using this command

serverless create --template aws-nodejs-typescript --path <project-name>

your handler.ts file will be looking like this

When you want to catch the errors and return a meaningful message you need to write it for each function. In some cases it is necessary but if all the functions are using the same code block it would be good to wrap them.

However typescript is only allowing using decorators for functions if the function is a part of the class.

What I did to use decorators is, define a class and a static function and add the decorator to that function. And you can return value from the decorator.

In that example it is returning the same error message if the functions which decorator is applied are throwing an exception.

That’s all. Please reach me for corrections or suggestions.

--

--