How to catch error in nestjs when a query fails
Answer a question
I am new to nestjs and was trying to convert my backend from nodejs to nestjs. Hope that makes sense? I am using `typeorm. But I am not sure as what could be the best of way of catching errors.
entity.ts
import { Entity, Column, PrimaryGeneratedColumn, PrimaryColumn } from 'typeorm';
@Entity()
export class Course {
@PrimaryColumn()
course: string;
@Column("varchar", { array: true })
subject: string[];
}
controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CourseService } from './course.service';
import { Course } from './course.entity';
@Controller('course')
export class CourseController {
constructor(private courseService: CourseService) {}
@Get()
getCourses(): Promise<Course[]> {
return this.courseService.findAll();
}
@Post()
addCourse(@Body() courseDto: Course[]) {
return this.courseService.create(courseDto);
}
}
service.ts
import { Injectable, Catch, ExceptionFilter, ArgumentsHost, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, QueryFailedError } from 'typeorm';
import { Course } from './course.entity';
@Injectable()
export class CourseService {
constructor(
@InjectRepository(Course)
private courseRepository: Repository<Course>,
) { }
catch(exception: any, host: ArgumentsHost) {
throw new Error("Error in course service." + exception.code);
}
findAll(): Promise<Course[]> {
return this.courseRepository.find();
}
create(courseDto) {
return this.courseRepository.insert(courseDto)
.catch((err: any) => {
// throw new ConflictException();
switch (err.name) {
case 'QueryFailedError':
console.log("**++**" + JSON.stringify(err));
// throw new Error("Error" + err.message + "" + err.detail);
// throw new ConflictException();
throw JSON.stringify(err); //"Error creating a course" + err.message + "::: " + err.detail;
default:
throw err;
}
});
}
}
Now, all I am able to throw is throw new ConflictException();. I wanted to throw different errors based on the result, like - 1. For duplicate record 2. Missing mandatory fields 3. etc
But not sure how can we handle and customize the same and also make full use of nestjs.
Like I see the below trace in console but 500, Internal server in postman -
{"message":"duplicate key value violates unique constraint \"PK_d7fc152bc721b3f55a56ed3ad33\"","name":"QueryFailedError","length":293,"severity":"ERROR","code":"23505","detail":"Key (course)=(II) already exists.","schema":"public","table":"course","constraint":"PK_d7fc152bc721b3f55a56ed3ad33","file":"d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\access\\nbtree\\nbtinsert.c","line":"535","routine":"_bt_check_unique","query":"INSERT INTO \"course\"(\"course\", \"subject\") VALUES ($1, $2)","parameters":["II",["A","B","C"]]}
[Nest] 12152 - 04/10/2020, 1:18:40 PM [ExceptionsHandler] {"message":"duplicate key value violates unique constraint \"PK_d7fc152bc721b3f55a56ed3ad33\"","name":"QueryFailedError","length":293,"severity":"ERROR","code":"23505","detail":"Key (course)=(II) already exists.","schema":"public","table":"course","constraint":"PK_d7fc152bc721b3f55a56ed3ad33","file":"d:\\pginstaller.auto\\postgres.windows-x64\\src\\backend\\access\\nbtree\\nbtinsert.c","line":"535","routine":"_bt_check_unique","query":"INSERT INTO \"course\"(\"course\", \"subject\") VALUES ($1, $2)","parameters":["II",["A","B","C"]]} +190924ms
Answers
How about passing the errors to your controller and let the controller throw those errors.
service.ts
create(courseDto) {
return this.courseRepository.insert(courseDto)
}
and in your controller.ts
import {
Controller,
Get,
Post,
HttpException,
HttpStatus,
} from '@nestjs/common';
...
@Post()
async addCourse(@Body() courseDto: Course[]) {
return await this.courseService.create(courseDto).catch(err => {
throw new HttpException({
message: err.message
}, HttpStatus.BAD_REQUEST);
})
}
https://docs.nestjs.com/exception-filters
更多推荐
所有评论(0)