NestJS 处理服务异常

标签 nestjs

我正在开发一个 NestJS 应用程序,其中我的服务并不总是由 Controller 或任何 http 请求调用。相反,某些服务由 cron 计划调用以定期获取数据。

在这种情况下处理错误的最佳方法是什么?我实现了一个“包罗万象”的异常过滤器,但是当我的服务被“内部”调用时(不是通过 Controller /请求),错误没有被捕获并且我有一个未捕获的 promise 错误。

最佳答案

在这里查看我的问题:Use global nest module in decorator

这个装饰器捕捉类方法的错误并记录它们。日志记录部分不是必需的,您可以实现自己的错误处理逻辑。

import { Inject } from '@nestjs/common';
import { LoggerService } from '../../logger/logger.service';

export function logErrorDecorator(bubble = false) {
  const injectLogger = Inject(LoggerService);

  return (target: any, propertyKey: string, propertyDescriptor: PropertyDescriptor) => {
    injectLogger(target, 'logger'); // this is the same as using constructor(private readonly logger: LoggerService) in a class

    //get original method
    const originalMethod = propertyDescriptor.value;

    //redefine descriptor value within own function block
    propertyDescriptor.value = async function(...args: any[]) {
      try {
        return await originalMethod.apply(this, args);
      } catch (error) {
        const logger: LoggerService = this.logger;

        logger.setContext(target.constructor.name);
        logger.error(error.message, error.stack);

        // rethrow error, so it can bubble up
        if (bubble) {
          throw error;
        }
      }
    };
  };
}

使用这个装饰器,您可以简单地将 logErrorDecorator() 添加到您的服务类方法中

关于NestJS 处理服务异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60402716/

相关文章:

typescript - Guards 和循环依赖中的服务注入(inject)

javascript - 无法在 Node 中导入 ESM .ts 模块

javascript - Nest 无法解析 UserModel 的依赖关系(?)

node.js - 如何访问上传到 nestjs 服务器的图片

graphql - NestJS + Typeorm + Graphql : correct design pattern for DTO in nested relations

javascript - NestJs:使用类验证器验证对象数组

typescript - 类验证器的匹配装饰器无法正常工作

swagger - 请求正文未在 Nest.js + Swagger 中显示

node.js - Nestjs-i18n 翻译 Handlebars 模板不起作用

typescript - 在 NestJS 中使用与 GraphQL 中的 Input 和 Object 类型相同的类