0
0
NestJSframework~30 mins

Catch decorator in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Create a Custom Catch Decorator in NestJS
📖 Scenario: You are building a NestJS backend service. You want to create a custom decorator that catches errors from a method and handles them gracefully.
🎯 Goal: Build a custom @CatchError decorator that wraps a method and catches any errors thrown, returning a friendly error message instead.
📋 What You'll Learn
Create a custom decorator function called CatchError
Use the decorator to wrap a method in a class
Catch any errors thrown inside the method
Return a string 'Error caught' when an error occurs
💡 Why This Matters
🌍 Real World
Custom decorators help add reusable behavior like error handling to methods in NestJS services, making code cleaner and more maintainable.
💼 Career
Understanding decorators is essential for backend developers working with NestJS, as they are widely used for middleware, validation, and error handling.
Progress0 / 4 steps
1
Create a simple service class with a method that throws an error
Create a class called TestService with a method dangerousMethod that throws an error with the message 'Something went wrong'.
NestJS
Need a hint?

Define a class and inside it a method that throws an error using throw new Error('Something went wrong').

2
Create the CatchError decorator function
Create a function called CatchError that returns a method decorator function. The decorator should accept target, propertyKey, and descriptor parameters.
NestJS
Need a hint?

Create a function that returns another function with the parameters target, propertyKey, and descriptor.

3
Implement error catching inside the decorator
Inside the CatchError decorator, save the original method from descriptor.value. Replace descriptor.value with a new function that calls the original method inside a try-catch block. If an error occurs, return the string 'Error caught'.
NestJS
Need a hint?

Save the original method, then replace it with a function that uses try-catch to handle errors and return 'Error caught'.

4
Apply the @CatchError decorator to the method
Add the @CatchError() decorator above the dangerousMethod in the TestService class.
NestJS
Need a hint?

Place @CatchError() directly above the method you want to decorate.