首页 > 解决方案 > NestJS 从守卫中抛出 http 异常(导出为库模块)

问题描述

我正在制作一个 Nestjs 库,其中包含一个守卫作为模块的一部分,

我尝试从守卫中抛出 http 错误,但是上下文在控制器中丢失了,它只会抛出 500。

如果我将库作为源代码而不是 dist 构建导入,它工作正常。

@Injectable()
export class SignedUrlGuard implements CanActivate {
    constructor(
        private readonly signedUrlService: SignedUrlService,
    ) { }

    canActivate(
        context: ExecutionContext,
    ): boolean | Promise<boolean> | Observable<boolean> {
        const request = context.switchToHttp().getRequest();
        return this.validateRequest(request, request.query);
    }

    private validateRequest(request: Request, query: Record<string, string>): boolean {
        try {
            return this.signedUrlService.isSignatureValid(request, query)
        } catch (error) {
            throw new ForbiddenException('Invalid url ,with custom error message')
        }
    }
}
"devDependencies": {
    "@nestjs/common": "^7.4.4",
    "@nestjs/core": "^7.4.4",
    "@types/express": "^4.17.8",
    "@types/node": "^14.14.2",
    "reflect-metadata": "^0.1.13",
    "rxjs": "^6.6.3",
    "typescript": "^4.0.3",
    "prettier": "^2.1.2",
    "eslint": "^7.12.0",
    "eslint-config-prettier": "^6.14.0",
    "@typescript-eslint/eslint-plugin": "^4.5.0",
    "@typescript-eslint/parser": "^4.5.0"
  },
  "peerDependencies": {
    "@nestjs/common": "^7.4.4",
    "@nestjs/core": "^7.4.4",
    "reflect-metadata": "^0.1.13"
  }

tsconfig

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "strict": true,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2019",
    "sourceMap": false,
    "outDir": "./dist",
    "rootDir": "./lib",
    "skipLibCheck": true
  },
  "include": ["lib/**/*"],
  "exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}

您可以在此处查看完整代码 https://github.com/vh13294/nestjs-signed-url

标签: typescriptexceptionnestjs

解决方案


通过基于文件的系统安装 npm 将不起作用

解决这个问题试试

npm 包

然后从 tgz 文件安装


推荐阅读