Decorator used for adding exceptions to :class:`SanicException`.
771432
def add_status_code(code):
    

    def class_decorator(cls):
        cls.status_code = code
        _sanic_exceptions[code] = cls
        return cls

    return class_decorator
624426
def subclass_exception(name, parents, module, attached_to=None):
    
    class_dict = {'__module__': module}
    if attached_to is not None:
        def __reduce__(self):
            # Exceptions are special - they've got state that isn't
            # in self.__dict__. We assume it is all in self.args.
            return (unpickle_inner_exception, (attached_to, name), self.args)

        def __setstate__(self, args):
            self.args = args

        class_dict['__reduce__'] = __reduce__
        class_dict['__setstate__'] = __setstate__

    return type(name, parents, class_dict)
981006
def return_false_on_exception(func):
    
    @wraps(func)
    def exceptfalse(*args, **kwargs):
        if not kwargs.pop('raise_exceptions', False):
            try:
                return func(*args, **kwargs)
            except Exception:
                return False
        else:
            return func(*args, **kwargs)
    return exceptfalse
1277688
def exception_handler(exceptionObj):
    """"""
    try:
        if isinstance(exceptionObj, Exception) and hasattr(exceptionObj, 'args'):
            if not (hasattr(exceptionObj, 'message' or hasattr(exceptionObj, 'msg'))):
                if len(exceptionObj.args) >= 1:
                    if type(exceptionObj.args[0]) == type(b''):
                        ob = json.loads(exceptionObj.args[0].decode('utf-8'))
                        if type(ob) == type({}) and ob['message']:
                            return ob['message']
                    else:

                        try:
                            if type(exceptionObj.args[0]) == type('') and exceptionObj.args[0][0] == 'b':
                                ob = json.loads(exceptionObj.args[0][2:-1])
                            else:
                                ob = json.loads(exceptionObj.args[0])
                            if type(ob) == type({}) and ob['message']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['message']
                            elif type(ob) == type({}) and ob['msg']:
                                try:
                                    return exception_handler(ob['message'])
                                except Exception as e:
                                    return ob['msg']
                            return str(json.loads(exceptionObj.args[0]))
                        except Exception as e:
                            return str(exceptionObj.args[0])
            elif hasattr(exceptionObj, 'msg'):
                return exceptionObj.msg
            elif hasattr(exceptionObj, 'message'):
                return exceptionObj.message
        elif type(exceptionObj) == type(''):
            try:
                ob = json.loads(exceptionObj)
                if type(ob) == type({}):
                    if ob['message']:
                        return ob['message']
                    elif ob['msg']:
                        return ob['msg']
                    else:
                        return ob
            except Exception as e:
                return exceptionObj

    except Exception as e:
        return e
189386
def extern_create_exception(self, context_handle, msg_ptr, msg_len):
    """"""
    c = self._ffi.from_handle(context_handle)
    msg = self.to_py_str(msg_ptr, msg_len)
    return c.to_value(Exception(msg))
1314225
def ignore_exceptions(f):
    """"""
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except:
            logging.exception("Ignoring exception in %r", f)
    return wrapped
24631
def exception(self, *args, **kwargs):
        """"""
        return self._log_kw(ERROR, args, kwargs, exc_info=True)
719403
def wrapply(func, *args, **kwargs):
    ''
    val = args[0]
    if val is None:
        return TypedWrapper(func, None)
    elif isinstance(val, TypedExceptionWrapper):
        tew = copy(val)
        tew.forwarded = True
        return tew
    elif isinstance(val, TypedWrapper):
        return val
    elif isinstance(val, Exception):
        return TypedWrapper(func, *args)

    try:
        return func(*args, **kwargs)
    except Exception as e:
        e.stacktrace = stacktrace()
        return TypedExceptionWrapper(func, *args, exception=e)
1253434
def raise_failure_exception(self, expect_or_allow='Allowed'):
        

        raise MockExpectationError(
            "{} '{}' to be called {}on {!r} with {}, but was not. ({}:{})".format(
                expect_or_allow,
                self._method_name,
                self._call_counter.error_string(),
                self._target.obj,
                self._expected_argument_string(),
                self._caller.filename,
                self._caller.lineno,
            )
        )
1059835
def _sanitise(self):
        
        for k in self.__dict__:
            if isinstance(self.__dict__[k], np.float32):  # np.float32 has a broken __str__ method
                self.__dict__[k] = np.float64(self.__dict__[k])
1333889
def pyError(self, type, value, traceback):
        '''
        '''
        sys.stderr.write("Exception thrown during EWrapper method dispatch:\n")
        print_exception(type, value, traceback)
795410
def ignore_exception(exception_class):
    """"""
    def _decorator(func):
        def newfunc(*args, **kwds):
            try:
                return func(*args, **kwds)
            except exception_class:
                pass
        return newfunc
    return _decorator
894095
def add_error(name=None, code=None, status=None):
    """"""
    if not name or not status or not code:
        raise Exception("Can't create Exception class %s: you must set both name, status and code" % name)
    myexception = type(name, (PyMacaronException, ), {"code": code, "status": status})
    globals()[name] = myexception
    if code in code_to_class:
        raise Exception("ERROR! Exception %s is already defined." % code)
    code_to_class[code] = myexception
    return myexception
1212181
def _wrapper(self, q, start):
        
        try:
            func_name = self.fnc.__name__
        except AttributeError:
            func_name = str(self.fnc)
        logger.debug("Running \"%s\" with parameters: \"%s\":\t%s/%s"
                     % (func_name, str(self.kwargs), round(time.time() - start), self.timeout))
        try:
            result = self.fnc(**self.kwargs)
            # let's log only first 50 characters of the response
            logger.debug("callback result = %s", str(result)[:50])
            q.put(result)
        except self.expected_exceptions as ex:
            logger.debug("expected exception was caught: %s", ex)
            q.put(False)
        except Exception as ex:
            logger.debug("adding exception %s to queue", ex)
            q.put(ex)
248556
def _exception_gather_guard(self, fn):
        

        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            try:
                return fn(*args, **kwargs)
            except UserException as e:
                self.exceptions.append(e)

        return wrapper
770696
def decorate_check_error(error_enum):
  """"""
  def decorator(func):
    @functools.wraps(func)
    def _check_error(*args, **kwargs):
      return check_error(func(*args, **kwargs), error_enum)
    return _check_error
  return decorator
1020860
public B annotatedService(Object service,
                              Function<Service<HttpRequest, HttpResponse>,
                                      ? extends Service<HttpRequest, HttpResponse>> decorator,
                              Object... exceptionHandlersAndConverters) {
        return annotatedService("/", service, decorator,
                                ImmutableList.copyOf(requireNonNull(exceptionHandlersAndConverters,
                                                                    "exceptionHandlersAndConverters")));
    }