Skip to content

Instantly share code, notes, and snippets.

@artalar
Created August 7, 2019 09:14
Show Gist options
  • Select an option

  • Save artalar/1af5c41434334113cd652e00b5c33dfb to your computer and use it in GitHub Desktop.

Select an option

Save artalar/1af5c41434334113cd652e00b5c33dfb to your computer and use it in GitHub Desktop.
Error logging
window.onerror = function (message, source, lineno, colno, error) {
if (typeof error === 'object' && error instanceof Error) {
try {
error = JSON.stringify(
error,
// по умолчанию поля ошибок не парсятся
Object.getOwnPropertyNames(error),
);
} catch (_) {
error = `${error.name}\n${error.message}\n${error.stack}`;
}
}
fetch('/log', {
method: 'POST',
headers: {
'Content-type': 'application/json',
'X-CSRF-Token': getCookie('...'),
},
body: JSON.stringify({
message,
source,
lineno,
colno,
error,
}),
});
// eslint-disable-next-line prefer-rest-params
next.apply(this, arguments);
};
server.route({
path: '/log',
method: 'POST',
handler(request, response) {
const payload = { ...request.payload };
if (typeof payload.message === 'string') {
try {
payload.message = JSON.parse(payload.message);
} catch (error) {
// ошибка парсинга строки `message`
// значит это не JSON, просто ничего с этим не делаем
}
}
console.log('---ERROR_LOG_START---');
console.log(new Date());
// eslint-disable-next-line no-console
console.dir(payload, { colors: true });
console.log('---ERROR_LOG_END---');
return response();
}
});
@artalar

artalar commented Aug 7, 2019

Copy link
Copy Markdown
Author

TODO: sendBeacon

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