简体   繁体   English

在ExpressJS中错误处理中间件以生成多个child_process

[英]Error Handling middleware in ExpressJS for spawn of multiple child_process

I have written a nice little error reporting middleware, that sits after all the GET and POST handling (after app.use(app.router); ). 我编写了一个很好的错误报告中间件,它位于所有GET和POST处理之后(在app.use(app.router);之后)。 See below. 见下文。

This works great for simple quick GET and POST that goes to the PostGIS database etc. 这对于转到PostGIS数据库等的简单快速GET和POST非常有用。

But I have one POST request that is designed to create a bunch of directories, a number of files, and then spawn 1 -> 8 child_processes tasks 但是我有一个POST请求,该请求旨在创建一堆目录,多个文件,然后生成1-> 8个child_processes任务

childProcess.execFile(job.config.FMEPath, ["PARAMETER_FILE", job.fmeParamFile], { cwd: job.root },

All that setup does not take much time (less than a second, and it is all async (I use the async library at one point to sequence 5 steps (see below). 所有的设置都不需要花费很多时间(不到一秒钟,而且都是异步的)(我在某一时刻使用异步库来排序5个步骤(请参见下文)。

My issue is error handling. 我的问题是错误处理。 Right now I return a response immediately before creating all the files and doing all the steps. 现在,在创建所有文件并执行所有步骤之前,我立即返回响应。 This means that next(err) is not working as expected. 这意味着next(err)不能按预期工作。 What is a good paradigm for reporting back the errors? 报告错误的良好范例是什么? I am using WINSTON to log errors [logger.log() ], but should I just log the errors on the server, or should I also report it to the original request. 我正在使用WINSTON记录错误[logger.log()],但是我应该只将错误记录在服务器上,还是应该将其报告给原始请求。 here is the current post request (and remember, I would have to keep the rest, and req and next object around for quite a while to be able to call next(err). 这是当前的发帖请求(记住,我将不得不保留其余的内容,并将req和next对象保留一段时间,以便能够调用next(err)。

exports.build = function (req, res, next) {
    var config = global.app.settings.config;
    var jobBatch = groupJobs(req.body.FrameList);
    var ticket = tools.newGuid("", true);
    var fileCount = req.body.FrameList.length * nitfMultiplier;
    var ts = timespan.fromSeconds(fileCount / config.TileRate);
    var estimate = ts.hours + ":" + tools.pad(ts.minutes, 2) + ":" + tools.pad(ts.seconds, 2);
    res.set({ 'Content-Type': 'application/json; charset=utf-8' });
    res.send({ ticket: ticket, maxTiles: fileCount, timeEstimate: estimate, tileRate: config.TileRate, wwwURL: config.WWWUrl });
    jobBatchRoot(req, res, jobBatch, config, ticket, next);
};

jobBatchRoot() (I will then go off and do a lot of processing, I did not include all that code. jobBatchRoot()(然后,我将进行大量处理,但我并未包含所有代码。

exports.bugs = function (err, req, res, next) {
    global.app.settings.stats.errors += 1;
    if (err.code == undefined) {
        err.code = 500;
        err.message = "Server Error";
    }
    res.status(err.code);
    logger.log('error', '%s url: %s status: %d \n', req.method, req.url, err.code, { query: req.query, body: req.body, message: err.message, stack: err.stack });
    var desc = req.method + " " + req.url;
    var body = util.format("%j", req.body);
    var query = util.format("%j", req.query);
    var stack = err.stack.split('\n');
    res.format({
        text: function () {
            res.send(util.format("%j", { title: err.message, code: err.code, desc: desc, query: query, message: err.message, stack: err.stack, body: body}));
        },

        html: function () {
            query = tools.pretty(req.query);
            res.render('error', { title: err.message, code: err.code, desc: desc, query: query, message: err.message, stack: stack, body: body });
        }, 

        json: function () {
            res.send({ title: err.message, code: err.code, desc: desc, query: query, message: err.message, stack: err.stack, body: body });
        }
    });

};

Perhaps I should be re-factoring this (maybe object oriented), anyway I thought I would post the full module here and all I am looking for is a few tips on structure, best practices. 也许我应该对此进行重构(也许是面向对象的),无论如何,我认为我将在此处发布完整的模块,而我正在寻找的只是关于结构和最佳实践的一些技巧。

var util = require('util');
var query = require("pg-query");
var timespan = require('timespan');
var _ = require('lodash');
var path = require('path');
var fs = require('fs');
var query = require("pg-query");
var async = require("async");
var childProcess = require("child_process");
var tools = require("../tools/tools");
var nitfMultiplier = 99;
var manifestVersionID = 5;

exports.setup = function (app) {
};

exports.estimate = function (req, res, next) {
    var config = global.app.settings.config;
    var fileCount = req.body.FrameList.length * nitfMultiplier;
    var ts = timespan.fromSeconds(fileCount / config.TileRate);
    var estimate = ts.hours + ":" + tools.pad(ts.minutes, 2) + ":" + tools.pad(ts.seconds, 2);
    res.set({ 'Content-Type': 'application/json; charset=utf-8' });
    res.send({ ticket: "Estimate", maxTiles: fileCount, timeEstimate: estimate, tileRate: config.TileRate, wwwURL: config.WWWUrl });
};

exports.build = function (req, res, next) {
    var config = global.app.settings.config;
    var jobBatch = groupJobs(req.body.FrameList);
    var ticket = tools.newGuid("", true);
    var fileCount = req.body.FrameList.length * nitfMultiplier;
    var ts = timespan.fromSeconds(fileCount / config.TileRate);
    var estimate = ts.hours + ":" + tools.pad(ts.minutes, 2) + ":" + tools.pad(ts.seconds, 2);
    res.set({ 'Content-Type': 'application/json; charset=utf-8' });
    res.send({ ticket: ticket, maxTiles: fileCount, timeEstimate: estimate, tileRate: config.TileRate, wwwURL: config.WWWUrl });
    jobBatchRoot(req, res, jobBatch, config, ticket, next);
};

function groupJobs(list) {
    var jobBatch = {};
    _.forEach(list, function (obj) {
        if (jobBatch[obj.type] == undefined) {
            jobBatch[obj.type] = [];
        }
        jobBatch[obj.type].push(obj);
    });
    return jobBatch;
};

function jobBatchRoot(req, res, jobBatch, config, ticket, next) {
    var batchRoot = path.join(config.JobsPath, ticket);
    fs.mkdir(batchRoot, function (err) {
        if (err) return next(err);
        var mapInfoFile = path.join(batchRoot, "MapInfo.json");
        var mapInfo = {
            Date: (new Date()).toISOString(),
            Version: manifestVersionID,
            Zoom: req.body.Zoom,
            CenterLat: req.body.CenterLat,
            CenterLon: req.body.CenterLon
        };
        fs.writeFile(mapInfoFile, tools.pretty(mapInfo), function (err) {
            if (err) return next(err);
            spawnJobs(req, res, batchRoot, mapInfo, config, ticket, jobBatch, next);
        });
    });
};

function spawnJobs(req, res, root, mapInfo, config, ticket, jobBatch, next) {
    _.forEach(jobBatch, function (files, key) {
        var job = {
            req: req,
            res: res,
            type: key,
            files: files,
            batchRoot: root,
            mapInfo: mapInfo,
            config: config,
            ticket: ticket,
            missingFiles: [],
            run: true,
            next: next
        };
        setup(job);
    });
};

function setup(job) {
    job.root = path.join(job.batchRoot, job.type);
    job.fmeParamFile = path.join(job.root, "fmeParameters.txt");
    job.fmeWorkSpace = path.join(job.config.LibrarianPath, "TileBuilder.fmw");
    job.fmeLogFile = path.join(job.root, "jobLog.log");
    job.errorLog = path.join(job.root, "errorLog.log");
    job.jobFile = path.join(job.root, "jobFile.json");
    job.manifestFile = path.join(job.root, "manifest.json");
    async.series({
        one: function (callback) {
            maxZoom(job, callback);
        },
        two: function (callback) {
            fs.mkdir(job.root, function (err) {
                if (err) return job.next(err);
                callback(null, "Job Root Created");
            });
        },
        three: function (callback) {
            makeParamFile(job, callback);
        },
        four: function (callback) {
            delete job.req;
            delete job.res;
            fs.writeFile(job.jobFile, tools.pretty(job), function (err) {
                if (err) return job.next(err);
                callback(null, "Wrote Job File");
            });
        },
        five: function (callback) {
            runJob(job, callback);
        },
        six: function (callback) {
            tileList(job, callback);
        },
        seven: function (callback) {
            finish(job, callback);
        },
    },
    function (err, results) {
        if (err) return job.next(err);
        console.log(tools.pretty(results));
    });
}

function maxZoom(job, callback) {
    var qString = util.format('SELECT type, "maxZoom" FROM portal.m_type WHERE type=\'%s\'', job.type);
    query(qString, function (err, rows, result) {
        if (err) {
            var err = new Error(queryName);
            err.message = err.message + " - " + qString;
            err.code = 400;
            return job.next(err);
        }
        job.maxZoom = rows[0].maxZoom - 1; // kludge for 2x1 root layer in leaflet
        return callback(null, "Got MaxZoom");
    });
}

function makeParamFile(job, callback) {
    var text = util.format("%s\n", job.fmeWorkSpace);
    text += util.format("--OutputDir %s\n", job.root);
    text += util.format("--LogFile %s\n", job.fmeLogFile);
    var source = "";
    _.forEach(job.files, function (file) {
        var path = ('development' == process.env.NODE_ENV) ? file.path.replace(job.config.SourceRootRaw, job.config.SourceRoot) : file.path;
        if (fs.existsSync(path)) {
            source += wrap(path, '\\"') + " ";
        }
        else {
            job.missingFiles.push(path);
        }
    });
    source = wrap(wrap(source, '\\"'), '"');
    text += "--Sources " + source;
    if (job.missingFiles.length == job.files.length) job.run = false;
    fs.writeFile(job.fmeParamFile, text, function (err) {
        if (err) return job.next(err);
        return callback(null, "Wrote Paramaters File");
    })
};

function wrap(content, edge) {
    return edge+content+edge;
    }

function runJob(job, callback) {
    if (!job.run) return callback(null, "Skipped JOB, no files");
    childProcess.execFile(job.config.FMEPath, ["PARAMETER_FILE", job.fmeParamFile], { cwd: job.root },
        function (err, stdout, stderr) {
            if (err) return job.next(err);
            job.stdout = stdout;
            job.stderr = stderr;
            var bar = "\n--------------------------------------------------------------------------------------------------------\n";
            var results = util.format("%s STDOUT: \n %s%s STDERR: \n %s", bar, job.stdout, bar, job.stderr);
            fs.appendFile(job.fmeLogFile, results, function (err) {
                return callback(err, "FME JOB " + job.type + " run completed");
            });
        });
}

function tileList(job, callback) {
    var tiles = [];
    var byteCount = 0;
    fs.readdir(job.root, function (err, files) {
        if (err) {
            logger.log('error', 'tileList directory read: %s \n', job.root, { message: err.message, stack: err.stack });
            return job.next(err);
        }
        async.each(files, function (file, done) {
            var fileName = file.split(".");
            fs.lstat(job.root + "\\" + file, function (err, stats) {
                if (!err && stats.isFile() && (fileName[1] == "png")) {
                    tiles.push({ id: fileName[0], size: stats.size });
                    byteCount += stats.size;
                };
                done(null);
            });
        }, function (err) {
        job.tileList = tiles;
        job.byteCount = byteCount;
        return callback(null, "got tile list");}
        );
    });
}

function finish(job, callback) {
    var manifest = {
        Date: (new Date()).toISOString(),
        Version: manifestVersionID,
        MaxZoom: job.maxZoom,
        Class: "OVERLAY",
        FileCount: job.tileList.length,
        Size: job.byteCount / (1024 * 1024), // Mbytes
        files: job.tileList
    };
    fs.writeFile(job.manifestFile, tools.pretty(manifest), function (err) {
        if (err) {
            logger.log('error', 'manifest write: %s \n', job.manifestFile, { message: err.message, stack: err.stack });
            return job.next(err);
        }
        return callback(null, "JOB " + job.type + " completed");
    });
}

I went and re-factored this. 我去重新构造了这个。 I created a module, with module.exports = function(..) {...} 我用module.exports = function(..){...}创建了一个模块

and then added lots of state and methods to create a class. 然后添加许多状态和方法来创建一个类。 That contains the Job definition. 包含Job定义。 So now I create the top level directories, return a response, and spawn the sub jobs. 因此,现在我创建顶层目录,返回响应,并生成子作业。 They all run async after the express response. 他们都在明确回应后异步运行。 But they should not get errors, and if they do, then I use WINSTON to log them in the server, and also return a job done information to the user when all the builds are done. 但是它们应该不会出错,如果出错了,那么我将使用WINSTON将它们记录在服务器中,并在完成所有构建后向用户返回作业完成的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM