Extracting message data

We can extract data from the message and put it in appropriate fields.

Remember what was said about a descriptive error message that was generated but not used? We can search it for the name of the entity that was not found. It can be found between double quotes, after the word "type". We can then extract this name with the following regex:

private readonly ENTITY_NAME_REGEX = /type\s\"(\w+)\"/;

Now, let's create a function that extracts a fragment from a text that matches a regex. We'll do so while creating the file common -> util -> regex.util.

export const extractFromText = (text: string, regex: RegExp) => {
  const matches = text.match(regex);
  const lastIndex = matches.length - 1;
  return matches[lastIndex];
};

The match() method returns an array that may contain many items but what matters to us is always in the last index. This link better explains this situation.

Back in the filter, let's then create a private method that extracts the entity name from the message.

private extractMessageData(message: string) {
  const entityName = extractFromText(message, this.ENTITY_NAME_REGEX);
  return { entityName };
}

There may be cases where we extract more data from the message, so we return the result in an object to maintain a pattern.

Then, once again in the catch() method, extract this name from the descriptive message.

const { entityName } = this.extractMessageData(exception.message);

And finally, create the message that will actually be returned.

const message = `${entityName} not found`;

The only thing that's left to do now is to setup the response.

Last updated