简体   繁体   English

快递中不清楚的错误处理

[英]Unclear error handling in express

I have a route to accept file uploads: 我有一条接受文件上传的途径:

In app.js 在app.js中

.
.
.
var upload = require('./routes/upload');
.
. 
.
app.use('/upload', upload);
.
.
.

/* Need to start the application with NODE_ENV=production */
app.use(function (err, req, res, next){
    if (res.headersSent) {
        return next(err)
    }
    res.status(500)
    res.render('An error occured while trying to serve your request. Please send us an email if the error recurs.')
});
app.listen(3000);

And in routes/upload.js, I check for file type before accepting the file and making an entry in the database. 在routes / upload.js中,我在接受文件并在数据库中进行输入之前检查文件类型。 I also check for error during file write which I try to pass to the error handler in app.js by calling next(err) inside handleFileUpload as shown below: 我还在文件写入期间检查错误,尝试通过在handleFileUpload中调用next(err)传递给app.js中的错误处理程序,如下所示:

var express = require('express');
var router = express.Router();
var path = require('path');
var mysql = require('mysql');
var multer = require('multer');
var fs = require('fs');
var db = require('../database');

var MAGIC_NUMBERS = {
    jpg:  'ffd8ffe0',
    jpg1: 'ffd8ffe1',
    png:  '89504e47'
}

/* Adapted from https://evdokimovm.github.io/javascript/nodejs/expressjs/multer/2016/11/03/Upload-files-to-server-using-NodeJS-and-Multer-package-filter-upload-files-by-extension.html */
function checkMagicNumbers(magic) {
    if (magic == MAGIC_NUMBERS.jpg || magic == MAGIC_NUMBERS.jpg1 || magic == MAGIC_NUMBERS.png)
         return true;
}

function handleFileUpload(req, res, next){
    var upload = multer({
        storage: multer.memoryStorage(),
    }).single('fileUpload');

    upload(req, res, function(err) {
        var buffer   = req.file.buffer;
        var magic    = buffer.toString('hex', 0, 4);
        var filename = req.file.fieldname + '-' + req.file.originalname.replace(/\s+/g,'') + '-' + Date.now() + path.extname(req.file.originalname);

        if (checkMagicNumbers(magic)) {
            fs.writeFile('/uploads/' + filename, buffer, 'binary', function(err) {
                if (err){
                    console.log(err);
                    return next(err);
                }
                else{
                    req.savedfilename = filename;
                    next();
                }
            })
        } else {
            res.end('File is not of the following accepted types: jpeg, jpg, png.');
        }
    });
}

function handleDatabaseInsert(req, res, next)
{   
    db.insertRecord(req.body.name, req.body.email, req.body.message,
         req.body.country, req.savedfilename, function(err, results){
            if(err)
                next(err);
    });
    res.end("Thank you for your participation! Please look forward to our email with updates.");
}

/* POST to Upload */
router.post('/', handleFileUpload, handleDatabaseInsert)

module.exports = router;

The issue is when I am trying to catch the error that may happen when trying to write the file and passing it to the error handler in app.js from inside handleFileUpload, the next middleware handleDatabaseInsert is called instead of the error handler that I made the app use towards the end of app.js before I make the app listen. 问题是当我试图捕获尝试写入文件并将其从handleFileUpload内部传递到app.js中的错误处理程序时可能发生的错误时,将调用下一个中间件handleDatabaseInsert而不是我制作的错误处理程序在我让应用程序监听之前,在app.js末尾使用该应用程序。

Is this the expected behavior? 这是预期的行为吗? I thought the function with 4 formal parameters will be called to handle the error? 我以为会调用带有4个形式参数的函数来处理错误?

Note: I am purposefully emulating write error by using a non-existent filepath, in this case /uploads/ instead of ./uploads/ 注意:我故意使用不存在的文件路径来模拟写入错误,在这种情况下,使用/ uploads /而不是./uploads/

Thanks! 谢谢!

If I understand correctly, you want to stop the request if there is some sort of error. 如果我理解正确,那么如果发生某种错误,您想停止该请求。 To do so you just stop calling next() 为此,您只需停止调用next()

Calling next() runs the next middleware function that was created If you don't want it to run the next middleware item don't call next() . 调用next()运行创建的下一个中间件函数。如果您不希望它运行下一个中间件,则不要调用next()

You would want to do something like res.send(500) in place of next() or something similar. 您可能想要执行诸如res.send(500)来代替next()或类似的操作。

If you want to create an error handler, you can do so as well: 如果要创建错误处理程序,也可以这样做:

http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling http://expressjs.com/en/guide/using-middleware.html#middleware.error-handling

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

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