import { ArgumentsHost, Catch, HttpServer } from '@nestjs/common' import { BaseExceptionFilter } from '@nestjs/core' import { debug, Debugger } from 'debug' import * as Rollbar from 'rollbar' import { HasuraExceptionError } from '../errors' @Catch() export class AllExceptionsMiddleware extends BaseExceptionFilter { private debug: Debugger = debug(this.constructor.name) constructor( readonly adapter: HttpServer, readonly rollbar = new Rollbar({ accessToken: globalThis.secret.rollbar.access_token, environment: globalThis.secret.rollbar.env, }), ) { super(adapter) } catch(exception: { message: string; stack: string }, host: ArgumentsHost): void { super.catch(exception, host) const request = host.switchToHttp().getRequest() const response = host.switchToHttp().getResponse() if (response.statusCode < 500) return if (Array.isArray(exception)) exception.forEach(value => this.logError(value, request)) else this.logError(exception, request) } private logError(exception: Record, request: any): void { const error = this.processError(exception) const logResult = this.rollbar .configure({ payload: { context: request.url, parameters: request.body, function: request.url.split('/')[1], }, }) .error(error.message, error) this.debug.extend('error:rollbar:result')(logResult) } private processError(error: Error | any): { message: string } | Error { if (error instanceof HasuraExceptionError) error.processToLog() return error } }