Search code examples
javascriptnode.jsmongodbexpresstry-catch

alternative to nested try catch in javascript


I am working on MEAN STACK web application and in nodejs I want to use async await with try catch block. In following example I want to make code in straight instead of using nested multiple try and catch. Here I need to pass different type of custom errors to front-end if any error arise.

EX :

public async create(req: Request, res: Response) {
    ...
    ...
    ...

    try {
        ...
        ...
        ...

        let userResult = await userModel.addBasickInfo(userData);

        ...
        ...
        ...

        try {
            ...
            ...
            ...

            let userAddressResult = await userProfileModel.addAddress(addressData);
            ...
            ...
            ...

            try {
                ...
                ...
                ...

                let userProfileResult = await userAddressModel.addProfile(profileData);
                ...
                ...
                ...

                return (<any>res).sendResponse(data, 'Information saved successfully');

            } catch (err) {
                return (<any>res).sendError(err.error ? err : new ErrorException('BadRequestError', "Error while adding user profile information"));
            }

        } catch (err) {
            return (<any>res).sendError(new ErrorException('BadRequestError', 'Error while adding user address'));
        }

    } catch (err) {
        return (<any>res).sendError(err.error ? err : new ErrorException('BadRequestError', 'Error while adding user information'));
    }
    
}

Please help me to improve this code.


Solution

  • You can try this pattern instead of nesting the try-catch block.

    public async create(req: Request, res: Response) {
    
        try {
            let userResult = await userModel.addBasickInfo(userData);
    
        } catch (err) {
            return (<any>res).sendError(err.error ? err : new ErrorException('BadRequestError', 'Error while adding user information'));
        }
    
        try {
            let userAddressResult = await userProfileModel.addAddress(addressData);
    
        } catch (err) {
            return (<any>res).sendError(new ErrorException('BadRequestError', 'Error while adding user address'));
        }
        try {
    
            let userProfileResult = await userAddressModel.addProfile(profileData);
            return (<any>res).sendResponse(data, 'Information saved successfully');
    
        } catch (err) {
            return (<any>res).sendError(err.error ? err : new ErrorException('BadRequestError', "Error while adding user profile information"));
        }
    }