Ayush
Ayush

Reputation: 23

strongloop loopback custom error handling

I am currently using loopback 3.2.1 The issue I am facing is unhandled error getting logged in the log files when access token expires. Doing google searches I came across this Unhandled error Here it is mentioned that we can have custom error logging middleware. I followed the instructions mentioned there and also referred the document for it. However I am getting the following error :

Error: Cannot apply .../server/middleware.staging.json: The middleware "./middleware/error-logger" in phase "final:after"is not defined in the main config.

current middleware.staging.json:

...
"final": {
    "loopback#urlNotFound": {}
  },
  "final:after": {
    "./middleware/error-logger": {},
    "strong-error-handler": {
      "params": {
        "debug": false,
        "includeStack": false,
        "log": false
      }
    }
  }

server/middleware/error-logger.js:

module.exports = function createErrorLogger(options) {
  return function logError(err, req, res, next) {
    // your custom error-logging logic goes here

    const status = err.status || err.statusCode;
    if (status >= 500) {
      // log only Internal Server errors
      console.log('Unhandled error for request %s %s: %s',
        req.method, req.url, err.stack || err);
    }

    // Let the next error handler middleware
    // produce the HTTP response
    next(err);
  };
}

What am I missing here ?

Upvotes: 1

Views: 1948

Answers (1)

Ayush
Ayush

Reputation: 23

Finally after looking at the code for loading the config files of loopback figured it out. Loopback is currently reading all the default config files and then merging them with the env specific file. So any configuration changes that need to be made has to be made in the default file with the values being set in the env specific files to make the change behave as required. For example in my case I was trying to add the middleware to the middleware.live.json but did not add it to the the default middleware.json file. So while executing mergePhaseConfig() the values present in the env specific files and searched for in the default file which was not present. Adding the middleware entry in the default file solved the issue. This is already mentioned in the documents but it skipped my mind today.

Upvotes: 1

Related Questions