Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
서버에서 나는 Exception을 텔레그램 봇으로 알림을 받아보자
import express from 'express';
import fetch from 'node-fetch';
const app = express();
app.get('/error/:number', (request, response) => {
try {
const result = occurError(request.params.number);
response.json(result);
} catch (error) {
errorHandler(request, response, error);
}
});
app.listen(3000, () => {
console.log('Web Server Listen 3000 port..!');
});
class HttpError extends Error {
constructor(status, code, message) {
super();
this.status = status || 500;
this.code = code || 'UNEXPECTED_ERROR';
this.message = message || 'What the Unexpected Error?!?!';
}
}
function occurError(numberParameter) {
if (!parseInt(numberParameter, 10)) {
throw new HttpError(403, 'PARAMETER_TYPE_EXCEPTION', 'numberParameter is require Number');
}
return 'This is Good Statement';
};
const TOKEN = '11111:TelegramBotToken'; // your Bot TOKEN
const TELEGRAM_BOT_URL = `https://api.telegram.org/bot${TOKEN}/sendMessage`;
const CHAT_ID = 123456789; // your chat ID
function errorHandler(request, response, error) {
const status = error.status || 500;
const code = error.code || 'UNEXPECTED_ERROR';
const message = error.message || error.toString();
if ([500, 403, 401].indexOf(status) >= 0) {
const text = `Occur ${code} Error..!\n\n- IP: ${request.ip}\n- URI: ${request.method} ${request.originalUrl}\n- HEADERS: ${JSON.stringify(request.headers)}\n- BODY: ${JSON.stringify(request.body)}\n\n- STATUS: ${status}\n- CODE: ${code}\n- STACK: ${error.stack}`;
fetch(TELEGRAM_BOT_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: CHAT_ID,
text
}),
}).then(result => result.json())
.catch(telegramError => console.error(telegramError));
}
response.status(status).send({ code, message });
}
Owner

uyu423 commented May 10, 2017

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment