【问题标题】:Is it good way to throw error from service in nestjs like it:像这样在nestjs中从服务中抛出错误的好方法吗:
【发布时间】:2022-01-12 12:00:33
【问题描述】:
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);
  }
}

好不好?

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案1】:

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

    对我来说,将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;
    }
    

    【讨论】:

    • 感谢您的回答)
    猜你喜欢
    • 2020-03-12
    • 2022-08-03
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多