const logger = require('../lib/logger');
const renderError = require('../layouts/500');

function getMessage(err) {
    if (!err) {
        return;
    }

    if (err.message) {
        return err.message;
    }

    if (err.body) {
        if (/^<!doctype/i.test(err.body)) {
            return err.body.replace(/\n/g, ' ').replace(/^.*<title>([^<]+)<\/title>.*$/, '$1');
        }

        return String(err.body);
    }

    return String(err);
}

/**
 * Обработчик брошенных через next ошибок
 */

module.exports = function (err, req, res, next) { // eslint-disable-line
    if (res.headersSent) {
        return next(err);
    }

    let displayedError;

    // Catch all
    err = err.error || err;

    displayedError = err;

    if (err.stack) {
        logger.error(`Exception: ${getMessage(err)}`, req, { stack: err.stack });
        displayedError = err.stack.split('\n').join('\\n');
    } else {
        logger.error(`Exception: ${getMessage(err)}`, req, { err: JSON.stringify(err) });
    }

    req.context = req.context || {};
    req.context.error = displayedError;

    renderError(req, res, next);
};
