What is the nestjs error handling approach (business logic error vs. http error)?

后端 未结 2 1181
情歌与酒
情歌与酒 2021-02-07 01:30

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 :

  1. Have individual servic
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 02:19

    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): Promise {
        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

提交回复
热议问题