Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  40] [ 1]  / answers: 1 / hits: 9948  / 2 Years ago, wed, january 12, 2022, 12:00:00
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?


More From » node.js

 Answers
6

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('nnn') + 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,
],
});
}
}




[#503] Tuesday, January 4, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brodyfrancisi

Total Points: 1
Total Questions: 102
Total Answers: 89

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;