0

I am wondering if in the following scenario am I am handling the right way the error and what is that I should return on error? Can you return statusCode on anything or only on response?

const storage = multer.diskStorage({
destination: function (req, file, cb) {
    if (err) {
        new Error({
            status: "INTERNAL SERVER ERROR"
        })
    }
    let filepath = './public/images/'
    cb(null, filepath)
},
filename: function (req, file, cb) {
    if (err) {
        new Error({
            status: "INTERNAL SERVER ERROR"
        })
    }
    let ext = file.originalname.split(".").pop();
    let filename = file.fieldname + '-' + Date.now() + '.' + ext
    //console.log(ext);
    cb(null, filename);
}

})

July333
  • 251
  • 1
  • 6
  • 15
  • Possible duplicate of [Node.js Best Practice Exception Handling](https://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling) – Harshal Yeole May 19 '18 at 13:33

1 Answers1

1

You can use status codes only on the response object.

For more details read this.

Try reading this question once.


The answer to your updated code:

You can send the error in the callback object. Read more about callback here.

The callback takes two params:

  1. Error
  2. Data

I will update your code below:

Updated Code:

    const storage = multer.diskStorage({
        destination: function(req, file, cb) {
            if (err) {
                cb(err, null);
            }
            let filepath = './public/images/'
            cb(null, filepath)
        },
        filename: function(req, file, cb) {
            if (err) {
                cb(err, null);
            }
            let ext = file.originalname.split(".").pop();
            let filename = file.fieldname + '-' + Date.now() + '.' + ext
            //console.log(ext);
            cb(null, filename);
        }
    })

This is how you ideally handle errors with the callback.

Try this and check if it works.

Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43
  • i edited my code according those answers. is this right now or do I need to handle at all in this case? – July333 May 19 '18 at 14:05
  • Okay, tell me this, you have incoming **req** object, correct? Then you must be having **res** object for that **req** object. And you can send the error in the **cb** instead of creating "new Error...." I would update my answer if you could answer my above questions – Harshal Yeole May 19 '18 at 14:10
  • I would update your code in the answer, check it out. – Harshal Yeole May 19 '18 at 14:17