<commit_before>import {createLocation} from 'history';
import {match} from 'react-router';

export function middleware (options) {
  const {cache = false, getHandler, getRoutes} = options;
  let {handler, routes} = options;

  if (!handler && !getHandler) { throw new Error('Missing handler.'); }
  if (!routes && !getRoutes) { throw new Error('Missing routes.'); }
  if (cache && getHandler) { handler = getHandler(); }
  if (cache && getRoutes) { routes = getRoutes(); }

  return function use (request, response, next) {
    const {query, url} = request;
    const location = createLocation(url);

    if (!cache && getHandler) { handler = getHandler(query); }
    if (!cache && getRoutes) { routes = getRoutes(query); }

    match({location, routes}, (error, redirect, props) => {
      if (error) { return response.status(500).send(error); }
      if (redirect) {
        const {pathname, search} = redirect;

        return response.redirect(302, pathname + search);
      }
      if (!props) { return next(); }

      function reply (string) {
        response.send(string);
        response.end();
      }

      handler({props, reply});
    });
  };
}<commit_msg>Updates middleware to utilize express's built in error handling.<commit_after>import {createLocation} from 'history';
import {match} from 'react-router';

export function middleware (options) {
  const {cache = false, getHandler, getRoutes} = options;
  let {handler, routes} = options;

  if (!handler && !getHandler) { throw new Error('Missing handler.'); }
  if (!routes && !getRoutes) { throw new Error('Missing routes.'); }
  if (cache && getHandler) { handler = getHandler(); }
  if (cache && getRoutes) { routes = getRoutes(); }

  return function use (request, response, next) {
    const {query, url} = request;
    const location = createLocation(url);

    if (!cache && getHandler) { handler = getHandler(query); }
    if (!cache && getRoutes) { routes = getRoutes(query); }

    match({location, routes}, (error, redirect, props) => {
      if (error) { return next(error); }
      if (redirect) {
        const {pathname, search} = redirect;

        return response.redirect(302, pathname + search);
      }
      if (!props) { return next(); }

      function reply (string) {
        response.send(string);
        response.end();
      }

      handler({props, reply});
    });
  };
}
{'fraction_non_alphanumeric': 0.15332771693344566, 'fraction_numerical': 0.0037910699241786015, 'mean_word_length': 3.302536231884058, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7283439', 'n_tokens_mistral': 699, 'n_tokens_neox': 682, 'n_words': 206}