0

I have a Express router with specific request handler:

router.post(def.doc_create, handle);
async function docCreate(req, res) {
    let metadata = mapper.mapObject(req.body, templates.document_create_rq);
    let relatedVers = mapper.mapArray('dms$relatedDocuments', templates.related_doc_vers, req.body).items;

    // if (req.body['dms$mchMetadata']) {
    try {
        let productInstanceIds = req.body['dms$mchMetadata']["pro$productInstanceIds"] || [];
    } catch (err) {
        throw new Error(err.message);
    }
....
}

'safeHandleReq' method will pick up the right handler for given route from the pre-initialised map and will call it:

class SafeRequestHandler {

    constructor(reqMappings) {
        this.mappings = reqMappings;
    }

    safeHandleReq(req, res) {
        try {
            let pair = _.find(this.mappings, {'url': req.url});
            return pair.handler(req, res);
        } catch (err) {
            return sendEnhaced(err, res);
        }
    }

}

with this handler being executed in try-catch I wanted to avoid UnhandledPromiseRejectionWarning: Unhandled promise rejection errors. This happens for example, where there is no such property in req.body that I'm asking for. Now exactly this happens in try-catch block I have shown here. The request's body does not contain dms$mchMetadata property at all. Now I have expected the catch block of the handler to be hit. But it's not. Even when I re-throw caught error in the 'docCreate' handler itself, safeHandleReq's handler catch block won't catch the error, but forementioned error is being written on the console instead.

I need to be able to catch all sorts of this errors in handler's catch block because there is many places where anticipations can go wrong and I need to return (somethong). When the error is not caught execution hangs and Express won't respond.

So why and what I need to do in order to be able to catch all errors from handler implementation in the safeHandleReq try-catch block? I need a systematic solution.

Thanks for recommendations!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
greengold
  • 1,184
  • 3
  • 18
  • 43
  • So `pair.handler(req, res)` returns a promise? Well `try`-`catch` doesn't catch promise rejections unless you use `await` syntax. Invoke the `.catch()` method instead. – Bergi Aug 23 '17 at 19:07
  • yees, you're right, I'm being dumb.. But still, as I was reading about async/await they was saying try-catch should be vital replacement for try/catch. it's not I can see now – greengold Aug 24 '17 at 09:41
  • It works fine in `docCreate`, doesn't it? The problem with `safeHandleReq` is that it is not an `async` function that `await`s the promise inside the `try`. – Bergi Aug 24 '17 at 20:07
  • right. `safeHandleReq` should be marked async and i need to await for the handler's processing. then I falls to `catch` branch as I thought it should do initially. Thanks for heads up! – greengold Aug 28 '17 at 10:05

0 Answers0