Issue
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?
Solution
In NestJs we have all exception filters so that we don't need to handle errors in all places
you can refer https://docs.nestjs.com/exception-filters
all-exceptions.filter.ts
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { object } from 'underscore';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const request = ctx.getRequest<CustomRequest>();
let internalStatus;
let status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
let message = exception.sqlMessage || exception.response || exception;
let error = exception.sqlState === 45000 ? 'Bad Request' : 'Bad Request';
request.log.timeTookToServe = Date.now() - request.log.timestamp;
request.log.message = message;
request.log.status = `${status}`;
if (exception instanceof TypeError) {
status = 400;
error = 'Bad Request';
message = exception.message
.substring(exception.message.indexOf('\n\n\n') + 1)
.trim();
}
if (status === 500) {
console.log(exception.sqlMessage, exception.sqlState, exception);
} else {
console.log(exception.sqlMessage, exception.sqlState, exception);
}
const errMessage = errJson[request.log['module']];
response.status(status).json({
status: exception.status || status,
error: error,
message: [
status === 403
? "Either you don't have the privilege or been logged out."
: message,
],
});
}
}
Answered By - Vignesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.