Search code examples
loopbackjsloopback

Change response body 404 in Loppback


I'm new to loopback. I'm trying override response body when model record not found.

this is the default response body from explorer:

{
  "error": {
    "statusCode": 404,
    "name": "Error",
    "message": "could not find a model with id 666",
    "code": "MODEL_NOT_FOUND",
    "stack": "..."
  }
}

my expected result:

{
    "status": 404,
    "message": "could not find a model with id 666"
}

Solution

  • https://loopback.io/doc/en/lb3/Defining-middleware.html#middleware-phases

    final - Deal with errors and requests for unknown URLs.

      app.middleware('final', function(err, req, res, next) {
        if (err && err.code === 'MODEL_NOT_FOUND') {
          res.statusCode = 404;
          res.json({status: 404, message: err.message});
        }else {
          next();
        }
      });
    

    Register the with a file in the boot directory, in a file pointed to by middleware.json, or in server.js.