UNPKG

@backtrace/nestjs

Version:
286 lines (272 loc) 11.8 kB
import { BacktraceClient } from '@backtrace/node'; export * from '@backtrace/node'; import { Injectable, Optional, HttpException, Inject, ConfigurableModuleBuilder, Global, Module } from '@nestjs/common'; import { BaseExceptionFilter } from '@nestjs/core'; import { catchError, throwError } from 'rxjs'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; var BacktraceExceptionHandler_1; let BacktraceExceptionHandler = BacktraceExceptionHandler_1 = class BacktraceExceptionHandler { constructor(options, client) { this._options = { ...BacktraceExceptionHandler_1.getDefaultOptions(), ...options, }; this._client = client; } handleException(err, host) { var _a; const client = (_a = this._client) !== null && _a !== void 0 ? _a : BacktraceClient.instance; if (!client) { if (this._options.skipIfClientUndefined) { return false; } throw new Error('Backtrace instance is unavailable. Initialize the client first.'); } if (!this.shouldSend(err)) { return false; } let attributes = { ...this.getBaseAttributes(host), ...this.getTypeAttributes(host), }; if (this._options.buildAttributes) { attributes = this._options.buildAttributes(host, attributes); } if (typeof err !== 'string' && !(err instanceof Error)) { client.send(String(err), attributes); } else { client.send(err, attributes); } return true; } shouldSend(error) { if (this._options.includeExceptionTypes && this.testException(error, this._options.includeExceptionTypes)) { return true; } if (this._options.excludeExceptionTypes && this.testException(error, this._options.excludeExceptionTypes)) { return false; } return true; } getBaseAttributes(host) { const contextType = host.getType(); return { 'request.contextType': contextType, }; } getTypeAttributes(host) { const type = host.getType(); switch (type) { case 'http': return this.getHttpAttributes(host.switchToHttp()); case 'rpc': return this.getRpcAttributes(host.switchToRpc()); case 'ws': return this.getWsAttributes(host.switchToWs()); default: return {}; } } getHttpAttributes(http) { const request = http.getRequest(); const expressRequest = request; return { 'request.url': expressRequest.url, 'request.baseUrl': expressRequest.baseUrl, 'request.method': expressRequest.method, 'request.originalUrl': expressRequest.originalUrl, 'request.protocol': expressRequest.protocol, 'request.hostname': expressRequest.hostname, 'request.httpVersion': expressRequest.httpVersion, }; } getRpcAttributes(rpc) { return { ['rpc.data']: rpc.getData(), }; } getWsAttributes(ws) { return { ['ws.data']: ws.getData(), }; } /** * Checks if given exception is matched by the filter, or any filter, if multiple are provided. * @param exception Exception to test. * @param filter Filter(s) to use. * @returns `true` if matched, `false` if not */ testException(exception, filter) { if (Array.isArray(filter)) { return filter.some((f) => exception instanceof f); } return filter(exception); } static getDefaultOptions() { return { excludeExceptionTypes: (error) => error instanceof HttpException && error.getStatus() < 500, skipIfClientUndefined: false, }; } }; BacktraceExceptionHandler = BacktraceExceptionHandler_1 = __decorate([ Injectable(), __param(1, Optional()), __metadata("design:paramtypes", [Object, BacktraceClient]) ], BacktraceExceptionHandler); let BacktraceExceptionFilter = class BacktraceExceptionFilter extends BaseExceptionFilter { constructor(handlerOrOptions, clientOrApplicationRef, maybeApplicationRef) { const applicationRef = (maybeApplicationRef !== null && maybeApplicationRef !== void 0 ? maybeApplicationRef : clientOrApplicationRef instanceof BacktraceClient) ? maybeApplicationRef : clientOrApplicationRef; super(applicationRef); if (handlerOrOptions instanceof BacktraceExceptionHandler) { this._handler = handlerOrOptions; return; } const options = handlerOrOptions; if (clientOrApplicationRef instanceof BacktraceClient) { this._handler = new BacktraceExceptionHandler(options, clientOrApplicationRef); } else { this._handler = new BacktraceExceptionHandler(options); } } catch(exception, host) { this._handler.handleException(exception, host); super.catch(exception, host); } }; BacktraceExceptionFilter = __decorate([ Injectable(), __param(0, Inject(BacktraceExceptionHandler)), __param(1, Inject(BacktraceClient)), __param(1, Optional()), __param(2, Optional()), __metadata("design:paramtypes", [Object, Object, Object]) ], BacktraceExceptionFilter); var BacktraceInterceptor_1; /** * Intercepts errors and sends them to Backtrace. */ let BacktraceInterceptor = BacktraceInterceptor_1 = class BacktraceInterceptor { constructor(handlerOrOptions, client) { if (handlerOrOptions instanceof BacktraceExceptionHandler) { this._handler = handlerOrOptions; return; } const options = handlerOrOptions; const handlerOptions = { ...options, buildAttributes: BacktraceInterceptor_1.extendBuildAttributes(options === null || options === void 0 ? void 0 : options.buildAttributes), }; if (client) { this._handler = new BacktraceExceptionHandler(handlerOptions, client); } else { this._handler = new BacktraceExceptionHandler(handlerOptions); } } intercept(context, next) { return next.handle().pipe(catchError((err) => { this._handler.handleException(err, context); return throwError(() => err); })); } static extendBuildAttributes(buildAttributes) { const getAttributes = (context, attributes) => { const controller = context.getClass().name; return { ...attributes, 'request.controller': controller, }; }; if (!buildAttributes) { return getAttributes; } return (context, attributes) => buildAttributes(context, getAttributes(context, attributes)); } }; BacktraceInterceptor = BacktraceInterceptor_1 = __decorate([ Injectable(), __param(0, Inject(BacktraceExceptionHandler)), __param(1, Optional()), __metadata("design:paramtypes", [Object, BacktraceClient]) ], BacktraceInterceptor); const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } = new ConfigurableModuleBuilder().build(); /** * Registers `BacktraceClient` and exports it. If the client is not passed, the global one is used. * If using the global instance, make sure to call `BacktraceClient.initialize` first. * * This module is global, you need to register it only once in your application. */ let BacktraceModule = class BacktraceModule extends ConfigurableModuleClass { }; BacktraceModule = __decorate([ Global(), Module({ providers: [ { provide: MODULE_OPTIONS_TOKEN, useFactory: () => BacktraceClient.instance, }, { provide: BacktraceClient, useFactory: (instanceOrOptions) => { var _a, _b; const instance = (_a = (instanceOrOptions instanceof BacktraceClient ? instanceOrOptions : instanceOrOptions === null || instanceOrOptions === void 0 ? void 0 : instanceOrOptions.client)) !== null && _a !== void 0 ? _a : BacktraceClient.instance; const skipIfClientUndefined = instanceOrOptions instanceof BacktraceClient ? false : (_b = instanceOrOptions === null || instanceOrOptions === void 0 ? void 0 : instanceOrOptions.options) === null || _b === void 0 ? void 0 : _b.skipIfClientUndefined; if (!instance && !skipIfClientUndefined) { throw new Error('Backtrace instance is not available. Initialize it first, or pass it into the module using register/registerAsync.'); } return instance; }, inject: [MODULE_OPTIONS_TOKEN], }, { provide: BacktraceExceptionHandler, useFactory: (instanceOrOptions) => { const options = instanceOrOptions instanceof BacktraceClient ? undefined : instanceOrOptions === null || instanceOrOptions === void 0 ? void 0 : instanceOrOptions.options; return new BacktraceExceptionHandler(options); }, inject: [MODULE_OPTIONS_TOKEN], }, BacktraceInterceptor, BacktraceExceptionFilter, ], exports: [BacktraceClient, BacktraceExceptionFilter, BacktraceExceptionHandler, BacktraceInterceptor], }) ], BacktraceModule); export { BacktraceExceptionFilter, BacktraceExceptionHandler, BacktraceInterceptor, BacktraceModule }; //# sourceMappingURL=bundle.mjs.map