#how can make this try catch horror code better any suggestion?

3 messages · Page 1 of 1 (latest)

barren sapphire
#

I am doing this try catch in every route.
Why? I am conserned about if any error inside route crash my server so I put this. will it not? idk.
Another one I am using fastify and I don't find other ways to return the response . {
Success: true,
Data: domainResponse,
Message: "Domain get successfull",
},

this code is horable. I am dumb , asking for how can I get around this

  @UseGuards(AuthGuard, CustomerGuard)
  @Get("/domain")
  async getMainDomain(@Req() req: customerRequestType) {
    try {
      const domainResponse = await this.db.query.sf_main_domain.findFirst({
        where: eq(schema.sf_main_domain.StoreKey, req.StoreKey),
        columns: { StoreKey: false },
      });

      throw new HttpException(
        {
          Success: true,
          Data: domainResponse,
          Message: "Domain get successfull",
        },
        HttpStatus.OK,
      );
    } catch (error) {
      if (error instanceof HttpException) {
        return error;
      }

      throw new HttpException(
        {
          Success: false,
          Message: "Server Error!",
        },
        HttpStatus.BAD_REQUEST,
      );
    }
  }```
gritty perch
#

In my case my controller is clean. It only handle reading the request object and handling response object.

The rest of the logic is inside my service. I wrap my service method with a try catch that handle my custom AppError that extends HttpException. From there if you need to do additional logging for the error you can simply do it from inside the AppError or using exception filter that catch those AppError.

For input validation I use zod, I simply send unknown data type to my service and then validate it using zod to get the right typescript type.