How to get error line using Nestjs avoiding duplicate code

Viewed 511

I made a controller on nestjs as below.

  @Post()
  public async addConfig(@Res() res, @Body() createConfigDto: CreateConfigDto) {
    let config = null;
    try {
      config = await this.configService.create(createConfigDto);
    } catch (err) {
      return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
        status: 500,
        message: 'Error: Config not created!',
      });
    }
    if (!config) {
      return res.status(HttpStatus.NOT_FOUND).json({
        status: 404,
        message: 'Not Found',
      });
    }
    return res.status(HttpStatus.OK).json({
      message: 'Config has been created successfully',
      config,
    });
  }

And there is a service in other file.

  public async create(createConfigDto: CreateConfigDto): Promise<IConfig> {
    do something 1

    do something 2

    do something 3

    return result;
  }

If an internal server error occurs among "do somehting 1,2 or 3" when I request to this api, it will gives me response 500.
But I want to know in which line the error happend.
Therefore I made catch line function.

const getStackTrace = () => {
  const obj = {};
  Error.captureStackTrace(obj, getStackTrace);
  return obj.stack;
};

And I wrap the code with this function, like this

  public async create(createConfigDto: CreateConfigDto): Promise<IConfig> {
    try{
    do something 1
    }catch(error){
      console.log(error)
      getTrace()
    }

    try{
    do something 2
    }catch(error){
      console.log(error)
      getTrace()
    }

    try{
    do something 3
    }catch(error){
      console.log(error)
      getTrace()
    }

    return result;
  }

But the problem is the service code will grow a lot with this trace function.
I want to know whether there is more efficient way avoiding duplicate code using nestJs for this case.
I think interceptor or execption filter help this.
But I don't know how to code for this case , since I 'm about to start using nestjs.

Thank you for reading my question.

0 Answers
Related