Process the request and return a JSON response. Catch errors and return the
    appropriate HTTP code.

def application(environ, start_response):
    '''
    Process the request and return a JSON response. Catch errors and return the
    appropriate HTTP code.
    '''
    # Instantiate APIClient once for the whole app
    saltenviron(environ)

    # Call the dispatcher
    try:
        resp = list(dispatch(environ))
        code = 200
    except HTTPError as exc:
        code = exc.code
        resp = str(exc)
    except salt.exceptions.EauthAuthenticationError as exc:
        code = 401
        resp = str(exc)
    except Exception as exc:
        code = 500
        resp = str(exc)

    # Convert the response to JSON
    try:
        ret = salt.utils.json.dumps({'return': resp})
    except TypeError as exc:
        code = 500
        ret = str(exc)  # future lint: disable=blacklisted-function

    # Return the response
    start_response(H[code], get_headers(ret, {
        'Content-Type': 'application/json',
    }))
    return (ret,)