在nestjs中的服务中抛出Http异常是个好方法吗?在 Nestjs 中处理服务错误的最佳方法是什么?
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;
Run Code Online (Sandbox Code Playgroud)
然后在控制器中使用 try catch 并抛出 HttpException。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
好不好?