Home > Software engineering >  Is it good way to throw error from service in nestjs like it:
Is it good way to throw error from service in nestjs like it:

Time:01-13

const movie = await this.movieService.getOne(movie_id);
if(!movie){
  throw new Error(
    JSON.stringify({
      message:'some message',
      status:'http status'
   })
  );
}
const rating = await this.ratingRepository.find({where:{movie});
return rating;

And after it use try catch in controller and throw HttpExeption.

async getAllByMovie(@Param('movie_id') movie_id:string):Promise<Rating[]>{
  try{
    const ratings = await this.ratingService.getAllRatingsByMovie(Number(movie_id));
    return ratings;
  }catch(err){
    const {message,status} = JSON.parse(err.message);
    throw new HttpExeption(message,status);
  }
}

Is it good or not?

CodePudding user response:

In general it's a good idea to throw business errors from your services and handle theses errors on controller layer. But there is room for improvement looking at your code:

To me it looks a bit odd to stringify the message and status in order to pass it to Error. You could create a custom Error that contains these properties:

class MyBusinessError extends Error {
  status: number;

  constructor(message: string, status: number) {
    super(message);
    this.status = status;
  }
}

But I suggest to decide on controller level which status should be returned from the API because this is http specific and should not be part of your business logic.

Also there are exception filters coming with NestJS that you can use to catch exceptions and transform them into http exceptions. With that you don't need to try-catch in every controller method. You can check for specific Error type using instanceof:

try {
  // ...
}
catch(err) {
  if(err instanceof MyBusinessError) {
    // handle business error
  }
  
  throw err;
}
  •  Tags:  
  • Related