Home > Mobile >  nest.js returning an empty string on try/catch
nest.js returning an empty string on try/catch

Time:05-19

I have a nest.js application and these two methods below, on the first method I need to call two requests, but if the second fails it must give me an empty string and not throw an error. On the second method I passed an empty string when the request fail. I don't know if it's a good practice, but It's the only way I found to solve this problem.

  async getData(): Promise<any> {
    try {
      const data1 = await this.service.getData1()

      // if this request fail, I need it to get an empty string
      const data2 = await this.service.getData2(data1.param)

    } catch(error) {
      throw Error(error)
    }
  }

  async getData2(): Promise<string> {
    try {
      return await lastValueFrom(...some url to request);

    } catch(error) {
      // returning empty string and not throwing an error
      return '';
    }
  }

CodePudding user response:

First, you have to separate Data1 and Data2 functions then Call Them From the getData Function here is an Example


  async getData(): Promise<any> {
    try {
      const data1 = await this.getData1()
      if(data1 === '') {

        const data2 = await this.getData2(param)

        if(data2 === '') {
          return 'no Data'
        }
      }
  

    } catch(error) {
      throw Error(error)
    }
  }

  async getData1() {
    try {
     return await this.yourService.functionToGetData1()
    } catch (error) {
     // Return Empty String If Error
     return ''
    }
  }

  async getData2(param: any) {
    try {
     return await this.yourService.functionToGetData2()
    } catch (error) {
     // Return Empty String If Error
     return ''
    }
  }

CodePudding user response:

That's fine if you ask me, if you want another way to do it would be with let.

let data2;

try {
  data2 = await this.service.getData2(data1.param);
} catch (error) {
  data2 = '';
}
  • Related