NestJS error handling approach


NestJS error handling approach



While using NestJS to create API's I was wondering which is the best way to handle errors/exception.
I have found two different approaches :


throw new Error()


catch


HttpException


BadRequestException


ForbiddenException


HttpException



There are pros and cons to both approeaches:


Error


HttpException


Http



I was wondering, which one (if any) os the "nest js" way of doing it ?



How do you handle this matter?




1 Answer
1



You may want to bind services not only to HTTP interface, but also for GraphQL or any other interface. So it is better to cast business-logic level exceptions from services to Http-level exceptions (BadRequestException, ForbiddenException) in controllers.



In the simpliest way it could look like


import { BadRequestException, Injectable } from '@nestjs/common';

@Injectable()
export class HttpHelperService {
async transformExceptions(action: Promise<any>): Promise<any> {
try {
return await action;
} catch (error) {
if (error.name === 'QueryFailedError') {
if (/^duplicate key value violates unique constraint/.test(error.message)) {
throw new BadRequestException(error.detail);
} else if (/violates foreign key constraint/.test(error.message)) {
throw new BadRequestException(error.detail);
} else {
throw error;
}
} else {
throw error;
}
}
}
}



and then






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

How to input without newline? (Python)

C++ thread error: no type named ‘type’ MINGW

Analog for TagView in flutter