How to solve too many try catch in Typescript?

We can use the try-catch statements to handle errors in TypeScript. Sometimes, we require adding more than one try-catch block in the code to handle multiple errors.

When we add multiple try-catch statements in the code, the code becomes unreadable, and it becomes a headache for developers to refactor. In this tutorial, we will learn to convert too many try-catch blocks into a single try-catch block which can manage multiple errors.

Syntax

Users can follow the syntax below to use the single try-catch block in TypeScript.

try {
    throw new Error("error_message");
    // this code will not be executed
}
catch (error) {
    // manage the error
}

In the above syntax, we throw the errors inside the try block and catch the error in the catch block.

Whenever we get any error in the try block, execution control directly goes to the catch statement without executing the other try block code.

The Problem: Too Many try-catch Blocks

In the example below, we have added four try-catch blocks. We are throwing errors with different messages from every try-catch block.

Users can see the error message printed from every catch block in the output.

try {
    console.log("Inside the first try block");
    throw new Error("first error message");
} catch (error) {
    console.log(error.message);
}

try {
    console.log("Inside the second try block");
    throw new Error("second error message");
} catch (error) {
    console.log(error.message);
}

try {
    console.log("Inside the third try block");
    throw new Error("Third error message");
} catch (error) {
    console.log(error.message);
}

try {
    console.log("Inside the fourth try block");
    throw new Error("Fourth error message");
} catch (error) {
    console.log(error.message);
}
Inside the first try block
first error message
Inside the second try block
second error message
Inside the third try block
Third error message
Inside the fourth try block
Fourth error message

From the above example, users can understand how code becomes unreadable and unclear when we use too many try-catch statements in a single code.

Solution 1: Using Function Wrappers

In the example below, we have created the solveProblems() function. It takes a function as a parameter and invokes that function in the try block. If the function throws any error, we can catch it in a single block.

function func2() {
    throw new Error("This error is from second function!");
}

function func3() {
    let num = 10;
    num.toPrecision(1000);
}

function solveProblems(func) {
    // calling the callback function in the try block
    try {
        func();
    } catch (error) {
        console.log(error.message);
    }
}

// calling functions
solveProblems(func2);
solveProblems(func3);
This error is from second function!
toPrecision() argument must be between 1 and 100

Solution 2: Error-Safe Function Factory

Another approach is to create a utility function that makes any function "safe" by wrapping it in error handling:

function makeSafe(fn) {
    return function(...args) {
        try {
            return fn.apply(this, args);
        } catch (error) {
            console.log("Error caught:", error.message);
            return null; // or any default value
        }
    };
}

// Risky operations
const riskyOperation1 = () => {
    throw new Error("Operation 1 failed");
};

const riskyOperation2 = () => {
    JSON.parse("invalid json");
};

// Create safe versions
const safeOperation1 = makeSafe(riskyOperation1);
const safeOperation2 = makeSafe(riskyOperation2);

// Execute safely
safeOperation1();
safeOperation2();
console.log("Program continues normally");
Error caught: Operation 1 failed
Error caught: Unexpected token i in JSON at position 0
Program continues normally

Solution 3: Promise-based Error Handling

For asynchronous operations, you can use Promises to centralize error handling:

function executeWithErrorHandling(operations) {
    operations.forEach(operation => {
        Promise.resolve()
            .then(operation)
            .catch(error => console.log("Async error:", error.message));
    });
}

const operations = [
    () => { throw new Error("First async error"); },
    () => { throw new Error("Second async error"); },
    () => console.log("This operation succeeds")
];

executeWithErrorHandling(operations);
This operation succeeds
Async error: First async error
Async error: Second async error

Best Practices

  • Use function wrappers to reduce repetitive try-catch blocks
  • Create utility functions for common error handling patterns
  • Consider async/await with centralized error handling for asynchronous code
  • Log errors consistently across your application

Conclusion

Multiple try-catch blocks make code unreadable and hard to maintain. Use function wrappers, error-safe factories, or Promise-based patterns to centralize error handling and keep your TypeScript code clean and manageable.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements