Skip to content

Commit

Permalink
LOGS: improve sentry logging
Browse files Browse the repository at this point in the history
  • Loading branch information
mvshmakov committed Jun 7, 2020
1 parent 07da4fc commit c61a9f6
Show file tree
Hide file tree
Showing 18 changed files with 62 additions and 98 deletions.
3 changes: 1 addition & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"google-news-rss": "^0.4.1",
"heapdump": "^0.3.15",
"helmet": "^3.22.0",
"make-error": "^1.3.6",
"node-fetch": "^2.6.0",
"pm2": "^4.4.0",
"pmx": "^1.6.7",
Expand Down
7 changes: 3 additions & 4 deletions src/api/v1/routes/debug.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import * as path from "path";
import * as heapdump from "heapdump";
import makeError from "make-error";
import { format } from "date-fns";
import { Router, Response, Request } from "express";

import Logger from "@/modules/Logger";
import BaseError from "@/modules/BaseError";

import { authMiddleware } from "../middlewares";

const SentryError = BaseError.createError("SentryError");
const TestSentryError = makeError("TestSentryError");

const debugRoutes = Router();

Expand Down Expand Up @@ -45,7 +44,7 @@ debugRoutes.get("/heapdump", [
debugRoutes.get("/debugSentry", [
authMiddleware,
(): void => {
throw SentryError("Sentry error!");
throw new TestSentryError("Test Sentry error!");
},
]);

Expand Down
4 changes: 0 additions & 4 deletions src/bin/starter.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import { join } from "path";

import * as Sentry from "@sentry/node";
import * as dotenv from "dotenv";
import program from "commander";

import { resolveSentryConfigSync } from "@/resolvers/config";

import Bot from "@/modules/Bot";
import Server from "@/modules/Server";
import Logger from "@/modules/Logger";
Expand Down Expand Up @@ -36,7 +33,6 @@ const starter = async (): Promise<void> => {
});

Logger.info(`Starting ${mode} mode...`);
Sentry.init(resolveSentryConfigSync());

switch (mode) {
case "debug":
Expand Down
10 changes: 5 additions & 5 deletions src/helpers/scenes.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import makeError from "make-error";
import * as tt from "telegraf/typings/telegram-types";
import { Markup, Stage, Extra } from "telegraf";

import { TelegrafContext } from "telegraf/typings/context";
import { SceneContextMessageUpdate } from "telegraf/typings/stage";

import BaseError from "@/modules/BaseError";
import track from "@/resolvers/metricaTrack";
import { MENU_SCENARIO } from "@/constants/scenarios";
import { MILITARY_STICKER_ID } from "@/constants/configuration";
import { TReplyFunction } from "@/typings/custom";

const { inlineKeyboard, urlButton } = Markup;

const EnsureFromIdError = BaseError.createError("EnsureFromIdError");
const EnsureMessageError = BaseError.createError("EnsureMessageError");
const EnsureFromIdError = makeError("EnsureFromIdError");
const EnsureMessageError = makeError("EnsureMessageError");

export const ensureFromId = (
from: tt.User | undefined,
Expand All @@ -25,7 +25,7 @@ export const ensureFromId = (
}

if (!(from && from.id)) {
throw EnsureFromIdError("EnsureFromIdError should never occur");
throw new EnsureFromIdError("EnsureFromIdError should never occur");
}

return from.id;
Expand All @@ -41,7 +41,7 @@ export const ensureMessageText = (
}

if (!(message && message.text)) {
throw EnsureMessageError("EnsureMessageError should never occur");
throw new EnsureMessageError("EnsureMessageError should never occur");
}

return message.text;
Expand Down
17 changes: 0 additions & 17 deletions src/modules/BaseError.ts

This file was deleted.

6 changes: 3 additions & 3 deletions src/modules/Firebase/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import * as firebase from "firebase-admin";
import makeError from "make-error";

import BaseError from "@/modules/BaseError";
import { TFirebaseConfig } from "@/resolvers/config";

const FirebaseError = BaseError.createError("FirebaseInitError");
const FirebaseError = makeError("FirebaseInitError");

export default abstract class AbstractFirebase {
private _instance: firebase.database.Database;
Expand All @@ -30,7 +30,7 @@ export default abstract class AbstractFirebase {
})
.database();
} catch (exception) {
throw FirebaseError("Cannot initialize Firebase");
throw new FirebaseError("Cannot initialize Firebase");
}
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/modules/Metrica.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import makeError from "make-error";
import BotMetrica, { TMetricaTrackFunction } from "bot-metrica";

import BaseError from "@/modules/BaseError";
import { resolveMetricaConfigSync } from "@/resolvers/config";

// TODO: all errors унести from classes
const MetricaInitError = BaseError.createError("MetricaInitError");
const MetricaInitError = makeError("MetricaInitError");

class Metrica {
private _instance: TMetricaTrackFunction;
Expand All @@ -20,7 +19,7 @@ class Metrica {
try {
this._instance = BotMetrica(counter, config);
} catch (exception) {
throw MetricaInitError("Cannot initialize BotMetrica");
throw new MetricaInitError("Cannot initialize BotMetrica");
}
}
}
Expand Down
15 changes: 7 additions & 8 deletions src/modules/Schedule/Downloader.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { join } from "path";
import { writeFileSync } from "fs";
import { Parser } from "htmlparser2";

import fetch from "node-fetch";
import BaseError from "@/modules//BaseError";
import makeError from "make-error";
import { Parser } from "htmlparser2";

const ScheduleDownloaderError = BaseError.createError(
"ScheduleDownloaderError",
);
const ScheduleDownloaderError = makeError("ScheduleDownloaderError");

class ScheduleDownloader {
private _baseUrl = "https://www.hse.ru";
Expand All @@ -18,7 +17,7 @@ class ScheduleDownloader {
const scheduleHref = await this._parseHtml(html);

if (scheduleHref === undefined) {
throw ScheduleDownloaderError("Cannot find href for schedule");
throw new ScheduleDownloaderError("Cannot find href for schedule");
}

await this._downloadAndSaveXlsx(`${this._baseUrl}${scheduleHref}`);
Expand All @@ -28,7 +27,7 @@ class ScheduleDownloader {
const response = await fetch(this._scheduleUrl);

if (!response.ok) {
throw ScheduleDownloaderError(
throw new ScheduleDownloaderError(
"Cannot find download html for schedule",
);
}
Expand Down Expand Up @@ -65,7 +64,7 @@ class ScheduleDownloader {

writeFileSync(this._schedulePath, xlsxContent, "utf8");
} catch (exception) {
throw ScheduleDownloaderError("Cannot download schedule xlsx");
throw new ScheduleDownloaderError("Cannot download schedule xlsx");
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/modules/Schedule/Parser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import makeError from "make-error";
import { Workbook, Worksheet, CellValue, CellRichTextValue } from "exceljs";

import {
Expand All @@ -11,7 +12,6 @@ import {
hasOnlyValuesFromArray,
} from "@/helpers/schedule";
import { head, capitalizeFirstLetter } from "@/helpers/general";
import BaseError from "@/modules/BaseError";

import {
TSchedule,
Expand All @@ -22,7 +22,7 @@ import {
TScheduleMetaDates,
} from ".";

const ScheduleParserError = BaseError.createError("ScheduleParserError");
const ScheduleParserError = makeError("ScheduleParserError");

// A bunch of legacy, that I was too lazy to refactor, sorry ¯\_(ツ)_/¯
class ScheduleParser {
Expand Down Expand Up @@ -122,7 +122,7 @@ class ScheduleParser {
try {
await workbook.xlsx.readFile(path);
} catch (exception) {
throw ScheduleParserError("Cannot read xlsx file");
throw new ScheduleParserError("Cannot read xlsx file");
}

const worksheet = workbook.getWorksheet(1);
Expand Down
9 changes: 4 additions & 5 deletions src/modules/Schedule/Storage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import makeError from "make-error";
import { existsSync, readFileSync, writeFileSync } from "fs";

import BaseError from "@/modules/BaseError";
import { resolveScheduleFileConfigSync } from "@/resolvers/config";

import { ScheduleParser, TScheduleObject } from ".";

const ScheduleStorageError = BaseError.createError("ScheduleStorageError");
const ScheduleStorageError = makeError("ScheduleStorageError");

class ScheduleStorage {
private _instance: TScheduleObject;
Expand Down Expand Up @@ -39,7 +38,7 @@ class ScheduleStorage {
this.dumpSchedule(this._instance, parsedSchedulePath);
} catch (exception) {
// TODO: нормальные трейсы у ошибок в логах
throw ScheduleStorageError("Cannot build ScheduleStorage");
throw new ScheduleStorageError("Cannot build ScheduleStorage");
}
}

Expand All @@ -51,7 +50,7 @@ class ScheduleStorage {
const jsonString = JSON.stringify(builtSchedule);
writeFileSync(parsedSchedulePath, jsonString, "utf8");
} catch (exception) {
throw ScheduleStorageError("Cannot dump ScheduleStorage");
throw new ScheduleStorageError("Cannot dump ScheduleStorage");
}
}
}
Expand Down
27 changes: 10 additions & 17 deletions src/modules/Server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,20 @@ import rateLimit from "express-rate-limit";
import addRequestId from "express-request-id";
import express, { Response } from "express";

import makeError from "make-error";
import * as Sentry from "@sentry/node";

import {
resolveBotConfigSync,
resolveEnvironmentSync,
resolveSentryConfigSync,
} from "@/resolvers/config";
import Bot from "@/modules/Bot";
import BaseError from "@/modules/BaseError";
import Logger, { ExpressLogger } from "@/modules/Logger";
import setupRoutes from "@/api/v1/routes";

const WebHookError = BaseError.createError("WebHookError");
const ExpressInitError = BaseError.createError("ExpressInitError");
const WebHookError = makeError("WebHookError");
const ExpressInitError = makeError("ExpressInitError");

interface CustomResponse extends Response {
sentry: string;
Expand Down Expand Up @@ -57,7 +58,7 @@ class ExpressApp {

private async _initializeBot(url: string, env: string): Promise<void> {
if (!this._bot || this._bot.instance === null) {
throw ExpressInitError(
throw new ExpressInitError(
'Provide bot and use property "{ useBot: true }"',
);
}
Expand All @@ -83,7 +84,7 @@ class ExpressApp {
);

if (!isWebhookSet) {
throw WebHookError("Cannot set WebHook in production");
throw new WebHookError("Cannot set WebHook in production");
}
}
}
Expand All @@ -92,6 +93,8 @@ class ExpressApp {
const { env, port, url } = resolveEnvironmentSync();

/* Use Sentry */
Sentry.init(resolveSentryConfigSync());

this._app.use(
Sentry.Handlers.requestHandler({
serverName: false,
Expand Down Expand Up @@ -143,17 +146,7 @@ class ExpressApp {
/* Routes */
setupRoutes(this._app);

this._app.use(
Sentry.Handlers.errorHandler({
shouldHandleError(error) {
// Capture all 404 and 500 errors
if (error.status === 404 || error.status === 500) {
return true;
}
return false;
},
}),
);
this._app.use(Sentry.Handlers.errorHandler());

/* Timeout checker */
// TODO: wtf??
Expand All @@ -171,7 +164,7 @@ class ExpressApp {
// @ts-ignore
this._app.use((_req, res: CustomResponse) => {
res.statusCode = 500;
res.end(res.sentry + "\n");
res.end(`${res.sentry ?? "Server Error"}\n`);
});

this._app.listen(port, () => {
Expand Down
2 changes: 2 additions & 0 deletions src/resolvers/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,10 @@ export const resolveNewsFileConfigSync = (): { newsPath: string } => ({

export const resolveSentryConfigSync = (): {
dsn: string;
debug: boolean;
release: string;
} => ({
dsn: process.env.SENTRY_DSN || "",
debug: true,
release: "hse-military-bot@2.0.0",
});
6 changes: 3 additions & 3 deletions src/resolvers/firebase/schedule.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BaseError from "@/modules/BaseError";
import makeError from "make-error";
import { FirebaseSchedule } from "@/modules/Firebase";

const FirebaseScheduleWriteResolverError = BaseError.createError(
const FirebaseScheduleWriteResolverError = makeError(
"FirebaseScheduleWriteResolverError",
);

Expand All @@ -12,7 +12,7 @@ export const resolveWriteScheduleSelection = async (
try {
await FirebaseSchedule.instance.ref(`/${category}`).set(data);
} catch (err) {
throw FirebaseScheduleWriteResolverError(
throw new FirebaseScheduleWriteResolverError(
"Error occurred in resolveWriteScheduleSelection resolver",
);
}
Expand Down

0 comments on commit c61a9f6

Please sign in to comment.