Updates the Flask app with Error Handlers for different Error Codes
345408
def _construct_error_handling(self):
        
        # Both path and method not present
        self._app.register_error_handler(404, ServiceErrorResponses.route_not_found)
        # Path is present, but method not allowed
        self._app.register_error_handler(405, ServiceErrorResponses.route_not_found)
        # Something went wrong
        self._app.register_error_handler(500, ServiceErrorResponses.lambda_failure_response)
569699
function (isGlobal, server, err, msg, session, resp, opts, cb) {
  let handler;
  if (isGlobal) {
    handler = server.app.get(Constants.RESERVED.GLOBAL_ERROR_HANDLER);
  } else {
    handler = server.app.get(Constants.RESERVED.ERROR_HANDLER);
  }
  if (!handler) {
    logger.debug('no default error handler to resolve unknown exception. ' + err.stack);
    utils.invokeCallback(cb, err, resp, opts);
  } else {
    if (handler.length === 5) {
      handler(err, msg, resp, session, cb);
    } else {
      handler(err, msg, resp, session, opts, cb);
    }
  }
}
1311055
function initErrorHandler (config) {
    // add error handler
    config.express.use(function(error, req, res, next) {
        // error must be object with stack
        if (typeof error !== 'object' || typeof error.stack !== 'string') {
            error = new Error(error)
        }
        // whether or not response will be JSON
        var json = req.query.json === '1' || req.query.json === 'true' || (req.xhr && req.query.json !== '0' && req.query.json !== 'false') ? true : false
        // set clean stack
        if (defined(stackUtils)) {
            error.stack = stackUtils.clean(error.stack)
        }
        // if error contains cookies then set cookies with response
        if (error.cookies) {
            // set cookies
            _.each(error.cookies, (value, name) => {
                setCookie(name, res, value)
            })
        }
        // get http code from error code
        var code = error.code
        // if code is not between 300 and 500 then set to 500
        if (!(code >= 300 && code <= 500)) {
            code = error.code = 500
        }
        // json response is expected
        if (json) {
            // code is for redirect
            if (code === 301 || code === 302) {
                res.json({
                    code: code,
                    redirect: true,
                    url: error.url,
                })
            }
            // if error is 409 conflict data should be current instance
            else if (code === 409) {
                // set http status code
                res.status(code)
                // send current instance data
                res.json(error.data)
            }
            // code is other error
            else {
                // get message
                var message = error.message || 'Unknown error'
                // build response
                var resData = {
                    error: message,
                    code: code,
                    data: error.data,
                }
                // add stack if in dev
                if (!isProd) {
                    resData.stack = error.stack.split('\n')
                    // remove last element from stack which is empty
                    resData.stack.pop()
                }
                // set http status code
                res.status(code)
                // send current instance data
                res.json(resData)
            }
        }
        // html response is expected
        else {
            // code is for redirect
            if (code === 301 || code === 302) {
                res.redirect(code, error.url)
            }
            // code is error
            else {
                // set http status code
                res.status(code)
                // create pretty printed json data
                if (error.data) {
                    error.prettyData = JSON.stringify(error.data, null, 4)
                }
                // build data for error template
                var data = {
                    error: error,
                    production: isProd,
                    session: req.session,
                }
                // add assets to template data
                _.merge(data, config.assets)
                // render error page
                res.render('error', data)
            }
        }
    })
}
1370448
function handleSuccess() {
  clearOutdatedErrors();

  var isHotUpdate = !isFirstCompilation;
  isFirstCompilation = false;
  hasCompileErrors = false;

  // Attempt to apply hot updates or reload.
  if (isHotUpdate) {
    tryApplyUpdates(function onHotUpdateSuccess() {
      // Only dismiss it when we're sure it's a hot update.
      // Otherwise it would flicker right before the reload.
      tryDismissErrorOverlay();
    });
  }
}
362090
def wrap_errorhandler(app):
        
        try:
            existing_handler = app.error_handler_spec[None][404][NotFound]
        except (KeyError, TypeError):
            existing_handler = None

        if existing_handler:
            app.error_handler_spec[None][404][NotFound] = \
                lambda error: handle_not_found(error, wrapped=existing_handler)
        else:
            app.error_handler_spec.setdefault(None, {}).setdefault(404, {})
            app.error_handler_spec[None][404][NotFound] = handle_not_found
1044819
def server_error_handling(&blk)
    begin
      blk.call
    rescue Sequel::DatabaseError => e
      if e.message =~ /duplicate key value/i
        raise Taps::DuplicatePrimaryKeyError, e.message
      else
        raise
      end
    end
  end
298893
def handle_wsgi_error(environ, exc):
    '''
    '''
    if isinstance(exc, tuple):
        exc_info = exc
        exc = exc[1]
    else:
        exc_info = True
    request = wsgi_request(environ)
    request.cache.handle_wsgi_error = True
    old_response = request.cache.pop('response', None)
    response = request.response
    if old_response:
        response.content_type = old_response.content_type
    logger = request.logger
    #
    if isinstance(exc, HTTPError):
        response.status_code = exc.code or 500
    else:
        response.status_code = getattr(exc, 'status', 500)
    response.headers.update(getattr(exc, 'headers', None) or ())
    status = response.status_code
    if status >= 500:
        logger.critical('%s - @ %s.\n%s', exc, request.first_line,
                        dump_environ(environ), exc_info=exc_info)
    else:
        log_wsgi_info(logger.warning, environ, response.status, exc)
    if has_empty_content(status, request.method) or status in REDIRECT_CODES:
        response.content_type = None
        response.content = None
    else:
        request.cache.pop('html_document', None)
        renderer = environ.get('error.handler') or render_error
        try:
            content = renderer(request, exc)
        except Exception:
            logger.critical('Error while rendering error', exc_info=True)
            response.content_type = 'text/plain'
            content = 'Critical server error'
        if content is not response:
            response.content = content
    return response
689055
def error_handling(cls, fn):
        """"""
        def wrapper(*args, **kwargs):
            try:
                result = fn(*args, **kwargs)
                return result
            except InvalidRequestError as e:
                write_exception(e)

                if hasattr(e, 'request'):
                    write_error_message('request {0}'.format(repr(e.request)))
                if hasattr(e, 'response'):
                    write_error_message('response {0}'.format(repr(e.response)))

                raise e
        return wrapper
930629
def handle_error(
        self,
        error: ValidationError,
        req: Request,
        schema: Schema,
        error_status_code: typing.Union[int, None] = None,
        error_headers: typing.Union[typing.Mapping[str, str], None] = None,
    ) -> "typing.NoReturn":
        
        error_class = exception_map.get(
            error_status_code or self.DEFAULT_VALIDATION_STATUS
        )
        if not error_class:
            raise LookupError("No exception for {0}".format(error_status_code))
        headers = error_headers
        raise error_class(
            body=json.dumps(error.messages).encode("utf-8"),
            headers=headers,
            content_type="application/json",
        )
753331
def setErrorHandler(self, errorhandler):
        
        class ErrorHandlerWrapper(ErrorHandler):
            def __init__(self, errorhandler):
                self.errorhandler = errorhandler
                self.last_exception = None

            def error(self, exception):
                if isinstance(exception, amplpython.AMPLException):
                    exception = AMPLException(exception)
                try:
                    self.errorhandler.error(exception)
                except Exception as e:
                    self.last_exception = e

            def warning(self, exception):
                if isinstance(exception, amplpython.AMPLException):
                    exception = AMPLException(exception)
                try:
                    self.errorhandler.warning(exception)
                except Exception as e:
                    self.last_exception = e

            def check(self):
                if self.last_exception is not None:
                    e, self.last_exception = self.last_exception, None
                    raise e

        errorhandler_wrapper = ErrorHandlerWrapper(errorhandler)

        class InnerErrorHandler(amplpython.ErrorHandler):
            def error(self, exception):
                errorhandler_wrapper.error(exception)

            def warning(self, exception):
                errorhandler_wrapper.warning(exception)

        self._errorhandler = errorhandler
        self._errorhandler_inner = InnerErrorHandler()
        self._errorhandler_wrapper = errorhandler_wrapper
        lock_and_call(
            lambda: self._impl.setErrorHandler(self._errorhandler_inner),
            self._lock
        )
802111
def handle_request_parsing_error(err, req, schema, error_status_code, error_headers):
    
    abort(error_status_code, errors=err.messages)
797732
function errors() {
        // handling 404 errors from config.express['404_redirect'] property
        if (config['404_redirect']) {
            server.use(function (req, res, next) {
                res.status(302)
                res.writeHead(302, { 'Location': config['404_redirect'] })
                res.end()
            })
        } else {
            server.use(function (req, res, next) {
                res.status(404).send({ message: 'not found' })
            })
        }

        if (errorHandlers.length) {
            for (let eh of errorHandlers) {
                server.use(wrapper(eh))
            }
        }

        //Default error handler
        server.use((err, req, res, next) => {
            if (!config.silent && !errorHandlers.length)
                app.drivers.logger.error('Unhandled server error', err)
            res.status(500)
               .json({
                   message: err.message,
                   stack: process.env.NODE_ENV === 'production' ? undefined : err.stack
               })
        })
    }
783000
def set_error_page(self, status, html_fpath):
        
        statuses = [403, 404, 500]

        status = int(status)

        if status not in statuses:
            raise ConfigurationError(
                'Code `%s` for `routing.set_error_page()` is unsupported. Supported: %s' %
                (status, ', '.join(map(str, statuses))))

        self._set('error-page-%s' % status, html_fpath, multi=True)

        return self._section
208181
def handle_error(self, e):
        
        got_request_exception.send(current_app._get_current_object(), exception=e)

        if not isinstance(e, HTTPException) and current_app.propagate_exceptions:
            exc_type, exc_value, tb = sys.exc_info()
            if exc_value is e:
                raise
            else:
                raise e

        headers = Headers()
        if isinstance(e, HTTPException):
            code = e.code
            default_data = {
                'message': getattr(e, 'description', http_status_message(code))
            }
            headers = e.get_response().headers
        else:
            code = 500
            default_data = {
                'message': http_status_message(code),
            }

        # Werkzeug exceptions generate a content-length header which is added
        # to the response in addition to the actual content-length header
        # https://github.com/flask-restful/flask-restful/issues/534
        remove_headers = ('Content-Length',)

        for header in remove_headers:
            headers.pop(header, None)

        data = getattr(e, 'data', default_data)

        if code and code >= 500:
            exc_info = sys.exc_info()
            if exc_info[1] is None:
                exc_info = None
            current_app.log_exception(exc_info)

        error_cls_name = type(e).__name__
        if error_cls_name in self.errors:
            custom_data = self.errors.get(error_cls_name, {})
            code = custom_data.get('status', 500)
            data.update(custom_data)

        if code == 406 and self.default_mediatype is None:
            # if we are handling NotAcceptable (406), make sure that
            # make_response uses a representation we support as the
            # default mediatype (so that make_response doesn't throw
            # another NotAcceptable error).
            supported_mediatypes = list(self.representations.keys())
            fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"
            resp = self.make_response(
                data,
                code,
                headers,
                fallback_mediatype = fallback_mediatype
            )
        else:
            resp = self.make_response(data, code, headers)

        if code == 401:
            resp = self.unauthorized(resp)
        return resp
1303725
function immutableAppHttpError (code, msg, data, cookies, headers) {
    // default to 400 application error
    if (!code) {
        code = 400
    }
    // set msg based on code if not set
    if (!msg) {
        msg = httpErrors[code] || 'Unspecified Error'
    }
    // create new error
    var err = new Error(msg)
    err.code = code
    err.data = data
    err.cookies = cookies
    err.headers = headers
    // throw error which will be handled by application framework
    throw err
}
512301
def _error_handling(self, res):
        

        # making the error handling generic so if an status_code starting with 2 doesn't exist, we raise the error
        if res.status_code // 100 != 2:
            error = self._get_response_json(res)
            raise exceptions.KeenApiError(error)
588463
def generate_crash_handler_decorator(error_decorator=None):
    """"""

    def crash_handler(f):
        """Return a decorator that reports failed api calls via the error_reporter,
        for use on every server endpoint"""

        @wraps(f)
        def wrapper(*args, **kwargs):
            """Generate a report of this api call, and if the call failed or was too slow,
            forward this report via the error_reporter"""

            data = {}
            t0 = timenow()
            exception_string = ''

            # Call endpoint and log execution time
            try:
                res = f(*args, **kwargs)
            except Exception as e:
                # An unhandled exception occured!
                exception_string = str(e)
                exc_type, exc_value, exc_traceback = sys.exc_info()
                trace = traceback.format_exception(exc_type, exc_value, exc_traceback, 30)
                data['trace'] = trace

                # If it is a PyMacaronException, just call its http_reply()
                if hasattr(e, 'http_reply'):
                    res = e.http_reply()
                else:
                    # Otherwise, forge a Response
                    e = UnhandledServerError(exception_string)
                    log.error("UNHANDLED EXCEPTION: %s" % '\n'.join(trace))
                    res = e.http_reply()

            t1 = timenow()

            # Is the response an Error instance?
            response_type = type(res).__name__
            status_code = 200
            is_an_error = 0
            error = ''
            error_description = ''
            error_user_message = ''

            error_id = ''

            if isinstance(res, Response):
                # Got a flask.Response object
                res_data = None

                status_code = str(res.status_code)

                if str(status_code) == '200':

                    # It could be any valid json response, but it could also be an Error model
                    # that pymacaron_core handled as a status 200 because it does not know of
                    # pymacaron Errors
                    if res.content_type == 'application/json':
                        s = str(res.data)
                        if '"error":' in s and '"error_description":' in s and '"status":' in s:
                            # This looks like an error, let's decode it
                            res_data = res.get_data()
                else:
                    # Assuming it is a PyMacaronException.http_reply()
                    res_data = res.get_data()

                if res_data:
                    if type(res_data) is bytes:
                        res_data = res_data.decode("utf-8")

                    is_json = True
                    try:
                        j = json.loads(res_data)
                    except ValueError as e:
                        # This was a plain html response. Fake an error
                        is_json = False
                        j = {'error': res_data, 'status': status_code}

                    # Make sure that the response gets the same status as the PyMacaron Error it contained
                    status_code = j['status']
                    res.status_code = int(status_code)

                    # Patch Response to contain a unique id
                    if is_json:
                        if 'error_id' not in j:
                            # If the error is forwarded by multiple micro-services, we
                            # want the error_id to be set only on the original error
                            error_id = str(uuid.uuid4())
                            j['error_id'] = error_id
                            res.set_data(json.dumps(j))

                        if error_decorator:
                            # Apply error_decorator, if any defined
                            res.set_data(json.dumps(error_decorator(j)))

                    # And extract data from this error
                    error = j.get('error', 'NO_ERROR_IN_JSON')
                    error_description = j.get('error_description', res_data)
                    if error_description == '':
                        error_description = res_data

                    if not exception_string:
                        exception_string = error_description

                    error_user_message = j.get('user_message', '')
                    is_an_error = 1


            request_args = []
            if len(args):
                request_args.append(args)
            if kwargs:
                request_args.append(kwargs)

            data.update({
                # Set only on the original error, not on forwarded ones, not on
                # success responses
                'error_id': error_id,

                # Call results
                'time': {
                    'start': t0.isoformat(),
                    'end': t1.isoformat(),
                    'microsecs': (t1.timestamp() - t0.timestamp()) * 1000000,
                },

                # Response details
                'response': {
                    'type': response_type,
                    'status': str(status_code),
                    'is_error': is_an_error,
                    'error_code': error,
                    'error_description': error_description,
                    'user_message': error_user_message,
                },

                # Request details
                'request': {
                    'params': pformat(request_args),
                },
            })

            populate_error_report(data)

            # inspect may raise a UnicodeDecodeError...
            fname = function_name(f)

            #
            # Should we report this call?
            #

            # If it is an internal errors, report it
            if data['response']['status'] and int(data['response']['status']) >= 500:
                report_error(
                    title="%s(): %s" % (fname, exception_string),
                    data=data,
                    is_fatal=True
                )

            log.info("")
            log.info(" <= Done!")
            log.info("")

            return res

        return wrapper

    return crash_handler