typescript - 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
解决方案
通过基于文件的系统安装 npm 将不起作用
解决这个问题试试
npm 包
然后从 tgz 文件安装
推荐阅读
- delphi - Delphi Spinedit:获取上一个值
- excel - 恢复 VBA 窗口的顺序
- php - 在 laravel 中创建记录时出错 - mongo Application
- ios - IOS 大标题 - 在启动新活动时捕捉
- php - 在前端将值显示为不同的值
- python - 想了解Python中某些代码行的含义
- regex - fail2ban-regex 与 alert_json 格式的 snort 日志文件不匹配
- javascript - 我正在使用 javascript 创建一个反应式杂货列表,当我单击它时我想更改列表项的颜色
- python - 使用 Python 进行文本预测
- ios - React Native 归档错误 - /ios/index.js。未找到