像这样在 nestjs 中从服务中抛出错误是不是一种好方法:

Is it good way to throw error from service in nestjs like it:

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;

然后在控制器中使用 try catch 并抛出 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);
  }
}

好不好?

一般来说,从您的服务中抛出业务错误并在控制器层处理这些错误是个好主意。 但是查看您的代码还有改进的余地:

对我来说,将 messagestatus 字符串化以将其传递给 Error 看起来有点奇怪。您可以创建一个包含这些属性的自定义错误:

class MyBusinessError extends Error {
  status: number;

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

但我建议在控制器级别决定应从 API 返回哪个状态,因为这是特定于 http 的,不应成为您业务逻辑的一部分。

还有 exception filters 随 NestJS 一起提供,您可以使用它来捕获异常并将它们转换为 http 异常。有了它,您就不需要在每个控制器方法中都尝试捕获。 您可以使用 instanceof:

检查特定的错误类型
try {
  // ...
}
catch(err) {
  if(err instanceof MyBusinessError) {
    // handle business error
  }
  
  throw err;
}