Mock Server
Guides
Error Handling

Error handling

There are two basic categories of errors that you'll encounter on Mock Server - errors encountered routing incoming requests and errors thrown by your code processing a request. For example, before requests are routed to your service, Mock Server parses the request based on the the Content-Type and this can throw an exception if a malformed body is sent. Although parsing failed, the request is still routed to your service with the error details so you can respond appropriately.

Lets look at an example using our create users route from before (here's the code again):

mock.define('/users', 'POST', function(req, res) {
    // validate username is present
    if (req.body.username === undefined) {
      return res.json(400, { error: { message: "Missing username" } })
    }
  
    return res.json({ status: "ok" })
  })

This service is expecting a JSON request body. If a request was sent with an invalid JSON body such as { username: "nick", "email": "nick@gmail.com" } then the initial parsing of the request will fail. When this occurs, the req.body object is replaced with the details of the error:

req.body = {
  isInvalid : true // set to true for parsing exceptions
  message   : "Failed to parse json body: " // details of the error
  raw       : { username: "nick", "email": "nick@gmail.com" } // the original payload
}

Handling malformed request data then is just a matter of checking for the req.body.isInvalid flag and responding appropriately. This applies to all request types - XML/SOAP, JSON etc. Here's what our updated create users route looks like:

mock.define('/users', 'POST', function(req, res) {
  
    if (req.body.isInvalid) {
      return res.json(400)
    }
  
    // validate username is present
    if (req.body.username === undefined) {
      return res.json(400, { error: { message: "Missing username" } })
    }
  
    return res.json({ status: "ok" })
  })