How to use exception method in Slash

Best Python code snippet using slash

exception-beautifier.js

Source:exception-beautifier.js Github

copy

Full Screen

1/*2 * Exception Beautifier plugin3 */4+function ($) {5 "use strict";6 var ExceptionBeautifier = function (el, options) {7 var self = this8 self.$el = $(el)9 self.options = options || {}10 // Init11 self.init()12 }13 ExceptionBeautifier.DEFAULTS = {}14 ExceptionBeautifier.REGEX = {15 phpline: /^(#[0-9]+)\s+(.+\.php)(?:\(([0-9]+)\))?\s*:(.*)/,16 artisan: /^(#[0-9]+)\s+(.+artisan)(?:\(([0-9]+)\))?\s*:(.*)/,17 internalLine: /^(#[0-9]+)\s+(\[internal function\]\s*:)(.*)/,18 defaultLine: /^(#[0-9]+)\s*(.*)/,19 className: /([a-z0-9]+\\[a-z0-9\\]+(?:\.\.\.)?)/gi,20 filePath: /((?:[A-Z]:)?(?:[\\\/][\w\.-_~@%]+)\.(?:php|js|css|less|yaml|txt|ini))(\(([0-9]+)\)|:([0-9]+)|\s|$)/gi,21 staticCall: /::([^( ]+)\(([^()]*|(?:[^(]*\(.+\)[^)]*))\)/,22 functionCall: /->([^(]+)\(([^()]*|(?:[^(]*\(.+\)[^)]*))\)/,23 closureCall: /\{closure\}\(([^()]*|(?:[^(]*\(.+\)[^)]*))\)/24 }25 ExceptionBeautifier.extensions = []26 ExceptionBeautifier.prototype.init = function () {27 var self = this,28 markup29 ExceptionBeautifier.extensions.forEach(function (extension) {30 if (typeof extension.onInit === 'function') {31 extension.onInit(self)32 }33 })34 markup = self.parseSource(self.$el.text())35 self.$el36 .addClass('plugin-exception-beautifier')37 .empty()38 .append(markup)39 }40 ExceptionBeautifier.prototype.parseSource = function (raw) {41 var self = this,42 source = raw,43 markup = {lines: []},44 start = 0,45 end46 /*47 * We only heavily parse stacktrace messages.48 * Standard messages are only applied a simple transform : newline to <br> and tab/spaces indentation to &nbsp;49 */50 if (source.indexOf('Stack trace:') < 0) {51 source = '{exception-beautifier-message-container}{exception-beautifier-message}' + self.formatMessage(source) + '{/exception-beautifier-message}{/exception-beautifier-message-container}'52 } else {53 end = source.indexOf('Stack trace:', start)54 markup.message = source.substring(start, end)55 start = source.indexOf('#', end)56 while ((end = source.indexOf('#', start + 1)) > 0) {57 markup.lines.push(self.parseLine(source.substring(start, end)))58 start = end59 }60 markup.lines.push(self.parseLine(source.substring(start)))61 source = '{exception-beautifier-message-container}' +62 '{exception-beautifier-message}' + self.formatMessage(markup.message) + '{/exception-beautifier-message}' +63 '{/exception-beautifier-message-container}' +64 '{exception-beautifier-stacktrace#div}'65 markup.lines.forEach(function (line) {66 source += '{exception-beautifier-stacktrace-line}' + self.formatStackTraceLine(line) + '{/exception-beautifier-stacktrace-line}'67 })68 source += '{/exception-beautifier-stacktrace#div}'69 ExceptionBeautifier.extensions.forEach(function (extension) {70 if (typeof extension.onParse === 'function') {71 extension.onParse(self)72 }73 })74 }75 markup = $(self.buildMarkup('{exception-beautifier-container}' + source + '{/exception-beautifier-container}'))76 return self.finalizeMarkup(markup, raw)77 }78 ExceptionBeautifier.prototype.parseLine = function (str) {79 var line = {},80 matches81 if ((matches = str.match(ExceptionBeautifier.REGEX.phpline)) || (matches = str.match(ExceptionBeautifier.REGEX.artisan))) {82 line.type = 'phpline'83 line.number = $.trim(matches[1])84 line.file = $.trim(matches[2])85 line.lineNumber = $.trim(matches[3])86 line.function = $.trim(matches[4])87 }88 else if (matches = str.match(ExceptionBeautifier.REGEX.internalLine)) {89 line.type = 'internal'90 line.number = $.trim(matches[1])91 line.internal = $.trim(matches[2])92 line.function = $.trim(matches[3])93 } else if (matches = str.match(ExceptionBeautifier.REGEX.defaultLine)) {94 line.type = 'default'95 line.number = $.trim(matches[1])96 line.function = $.trim(matches[2])97 }98 return line99 }100 ExceptionBeautifier.prototype.formatMessage = function (str) {101 var self = this102 return self.formatLineCode(103 str104 .replace(/^\s+/, '')105 .replace(/\r\n|\r|\n/g, '{x-newline}')106 .replace(/\t| {2}/g, '{x-tabulation}')107 )108 }109 ExceptionBeautifier.prototype.formatFilePath = function (path, line) {110 return '{exception-beautifier-file}' + path + '{/exception-beautifier-file}'111 }112 ExceptionBeautifier.prototype.formatStackTraceLine = function (line) {113 var self = this114 if (line.function) {115 line.function = self.formatLineCode(line.function)116 }117 switch (line.type) {118 case 'phpline':119 return '{exception-beautifier-stacktrace-line-number}' + line.number + '{/exception-beautifier-stacktrace-line-number}' +120 self.formatFilePath(line.file, line.lineNumber) +121 '{exception-beautifier-line-number}(' + line.lineNumber + '):{/exception-beautifier-line-number} ' +122 '{exception-beautifier-stacktrace-line-function}' + line.function + '{/exception-beautifier-stacktrace-line-function}'123 case 'internal':124 return '{exception-beautifier-stacktrace-line-number}' + line.number + '{/exception-beautifier-stacktrace-line-number}' +125 '{exception-beautifier-stacktrace-line-internal}' + line.internal + '{/exception-beautifier-stacktrace-line-internal}' +126 '{exception-beautifier-stacktrace-line-function}' + line.function + '{/exception-beautifier-stacktrace-line-function}'127 case 'default':128 return '{exception-beautifier-stacktrace-line-number}' + line.number + '{/exception-beautifier-stacktrace-line-number}' +129 '{exception-beautifier-stacktrace-line-function}' + line.function + '{/exception-beautifier-stacktrace-line-function}'130 }131 return ''132 }133 ExceptionBeautifier.prototype.formatLineCode = function (str) {134 var self = this135 if (str.match(/^\s*(call_user_func|spl_autoload_call)/)) {136 str = str.replace(/^\s*(?:call_user_func|spl_autoload_call)([^(]*)\((.*)\)/, function (str, suffix, parameters) {137 return '{exception-beautifier-system-function}call_user_func' + suffix + '({/exception-beautifier-system-function}' +138 self.formatFunctionParameters(parameters) +139 '{exception-beautifier-system-function}){/exception-beautifier-system-function}'140 })141 } else if (str.match(ExceptionBeautifier.REGEX.closureCall)) {142 str = str.replace(ExceptionBeautifier.REGEX.closureCall, function (str, parameters) {143 return '{exception-beautifier-function}{closure}({/exception-beautifier-function}' +144 self.formatFunctionParameters(parameters) +145 '{exception-beautifier-function}){/exception-beautifier-function}'146 })147 } else if (str.match(ExceptionBeautifier.REGEX.functionCall)) {148 str = str.replace(ExceptionBeautifier.REGEX.functionCall, function (str, functionName, parameters) {149 return '{exception-beautifier-function}→' + functionName + '({/exception-beautifier-function}' +150 self.formatFunctionParameters(parameters) +151 '{exception-beautifier-function}){/exception-beautifier-function}'152 })153 } else if (str.match(ExceptionBeautifier.REGEX.staticCall)) {154 str = str.replace(ExceptionBeautifier.REGEX.staticCall, function (str, functionName, parameters) {155 return '{exception-beautifier-function}::' + functionName + '({/exception-beautifier-function}' +156 self.formatFunctionParameters(parameters) +157 '{exception-beautifier-function}){/exception-beautifier-function}'158 })159 }160 str = str.replace(ExceptionBeautifier.REGEX.filePath, function (str, path, line, lineNumber, altLineNumber) {161 return self.formatFilePath(path, (lineNumber || '') + (altLineNumber || '')) +162 ($.trim(line).length > 0 ? ('{exception-beautifier-line-number}' + line + '{/exception-beautifier-line-number}') : ' ')163 })164 str = str.replace(ExceptionBeautifier.REGEX.className, function (str, name) {165 return '{exception-beautifier-class}' + name + '{/exception-beautifier-class}'166 })167 return str168 }169 ExceptionBeautifier.prototype.formatFunctionParameters = function (parameters) {170 return parameters171 .replace(/^([0-9]+)|([^a-z\\])([0-9]+)$|^([0-9]+)([^a-z\\])|([^a-z\\])([0-9]+)([^a-z\\])/g, '$2$6{exception-beautifier-number}$1$3$4$7{/exception-beautifier-number}$5$8')172 .replace(/^Array$|([^a-z\\])Array$|^Array([^a-z\\])|([^a-z\\])Array([^a-z\\])/g, '$1$3{exception-beautifier-code}Array{/exception-beautifier-code}$2$4')173 .replace(/^Closure$|(\()Closure(\))/g, '$1{exception-beautifier-code}Closure{/exception-beautifier-code}$2')174 .replace(/Object\(([^)]+)\)/g, '{exception-beautifier-code}Object({/exception-beautifier-code}$1{exception-beautifier-code}){/exception-beautifier-code}')175 .replace(/"((?:\\.|[^"])*)"/g, '{exception-beautifier-string}"$1"{/exception-beautifier-string}')176 .replace(/'((?:\\.|[^'])*)'/g, '{exception-beautifier-string}\'$1\'{/exception-beautifier-string}')177 }178 ExceptionBeautifier.prototype.buildMarkup = function (str) {179 var self = this,180 start = str.indexOf('{exception-beautifier-'),181 cssOffset = 'exception-beautifier-'.length,182 end, endtag, tmp, matches, tag, html, css, attrs, markup = ''183 if (start >= 0) {184 if (start > 0) {185 markup += self.buildMarkup(str.substring(0, start))186 }187 while (start >= 0) {188 end = endtag = str.indexOf('}', start)189 if ((tmp = str.indexOf(' ', start)) >= 0) {190 end = Math.min(end, tmp)191 }192 tag = str.substring(start + 1, end)193 end = str.indexOf('{/' + tag + '}', start)194 start = str.indexOf('}', start)195 if (end < 0) {196 throw 'Markup error tag {' + tag + '} not closed'197 }198 html = 'span'199 attrs = ''200 css = tag201 if (matches = tag.match(/(.+)#([a-z]+)$/)) {202 css = matches[1]203 html = matches[2]204 }205 css = 'beautifier-' + css.substr(cssOffset)206 if (tmp >= 0 && tmp < endtag) {207 attrs = str.substring(tmp, endtag)208 }209 markup += '<' + html + ' class="' + css + '"' + attrs + '>'210 markup += self.buildMarkup(str.substring(start + 1, end))211 markup += '</' + html + '>'212 end = end + ('{/' + tag + '}').length213 start = str.indexOf('{exception-beautifier-', end)214 if (start > end || start < 0) {215 markup += self.buildMarkup(str.substring(end, start < 0 ? undefined : start))216 }217 }218 } else {219 markup += $.oc.escapeHtmlString(str)220 .replace(/\{x-newline\}/g, '<br>')221 .replace(/\{x-tabulation\}/g, '&nbsp;&nbsp;')222 }223 return markup224 }225 ExceptionBeautifier.prototype.finalizeMarkup = function (markup, source) {226 var stacktrace,227 messageContainer,228 tabs229 markup.find('.beautifier-file').each(function () {230 $(this).find('.beautifier-class').each(function () {231 var $el = $(this)232 $el.replaceWith($el.text())233 })234 })235 markup.find('.beautifier-file+.beautifier-line-number').each(function () {236 var $el = $(this)237 $el.appendTo($el.prev())238 })239 messageContainer = markup.find('.beautifier-message-container')240 stacktrace = markup.find('.beautifier-stacktrace')241 .addClass('hidden')242 if (!!stacktrace.length) {243 $('<a class="beautifier-toggle-stacktrace" href="javascript:;"><span>' + $.oc.lang.get('eventlog.show_stacktrace') + '</span></a>')244 .appendTo(messageContainer)245 .on('click', function (event) {246 var $el = $(this)247 event.preventDefault()248 event.stopPropagation()249 $('.beautifier-stacktrace', markup).toggleClass('hidden')250 $el.hide()251 })252 }253 tabs = $('<div class="control-tabs content-tabs tabs-inset">' +254 '<ul class="nav nav-tabs">' +255 '<li class="active"><a href="#beautifier-tab-formatted">' + $.oc.lang.get('eventlog.tabs.formatted') + '</a></li>' +256 '<li><a href="#beautifier-tab-raw">' + $.oc.lang.get('eventlog.tabs.raw') + '</a></li>' +257 '</ul><div class="tab-content">' +258 '<div class="tab-pane pane-inset active" id="beautifier-tab-formatted"></div>' +259 '<div class="tab-pane pane-inset" id="beautifier-tab-raw"></div>' +260 '</div></div>')261 if (source.indexOf('Message-ID:') > 0) {262 markup = '<div class="beautifier-formatted-content">' + source.trim().replace(/\r\n|\r|\n/g, '<br>').replace(/ {2}/g, '&nbsp;&nbsp;') + '</div>'263 }264 tabs.find('#beautifier-tab-formatted').append(markup)265 tabs.find('#beautifier-tab-raw').append('<div class="beautifier-raw-content">' + $.oc.escapeHtmlString(source.trim()).replace(/\r\n|\r|\n/g, '<br>').replace(/ {2}/g, '&nbsp;&nbsp;') + '</div>')266 tabs.ocTab({closable: false})267 return tabs268 }269 // EXCEPTION BEAUTIFIER PLUGIN DEFINITION270 // ============================271 $.fn.exceptionBeautifier = function (option) {272 var args = arguments,273 result274 this.each(function () {275 var $this = $(this)276 var data = $this.data('oc.exceptionBeautifier')277 var options = $.extend({}, ExceptionBeautifier.DEFAULTS, $this.data(), typeof option == 'object' && option)278 if (!data) $this.data('oc.exceptionBeautifier', (data = new ExceptionBeautifier(this, options)))279 if (typeof option == 'string') result = data[option].call($this)280 if (typeof result != 'undefined') return false281 })282 return result ? result : this283 }284 $.fn.exceptionBeautifier.Constructor = ExceptionBeautifier285 $(document).render(function () {286 $('[data-plugin="exception-beautifier"]').exceptionBeautifier()287 })...

Full Screen

Full Screen

MangroveException.py

Source:MangroveException.py Github

copy

Full Screen

1#TODO: Please Read Readme.rst of errors before defining any new exception2class MangroveException(Exception):3 def __init__(self, message, data=None):4 assert data is None or type(data) is tuple5 self.message = message6 self.data = data7 def __str__(self):8 return self.message9class DataObjectAlreadyExists(MangroveException):10 def __init__(self, dataobject_name, param, value, existing_name=''):11 error_message = u"%s with %s = %s already exists." % (dataobject_name, param, value)12 MangroveException.__init__(self, error_message, (param, value, dataobject_name, existing_name))13class EmptyRowException(MangroveException):14 def __init__(self):15 error_message = u"The row is empty"16 MangroveException.__init__(self, message=error_message)17class DataObjectNotFound(MangroveException):18 def __init__(self, dataobject_name, param, value):19 error_message = u"%s with %s = %s not found." % (dataobject_name, param, value)20 MangroveException.__init__(self, error_message, (dataobject_name, param, value))21class EntityTypeAlreadyDefined(MangroveException):22 pass23class FormModelDoesNotExistsException(MangroveException):24 def __init__(self, questionnaire_code):25 error_message = u"The questionnaire with code %s does not exist." % questionnaire_code if questionnaire_code else "The questionnaire does not exist."26 MangroveException.__init__(self, error_message, (questionnaire_code, ))27class ProjectPollCodeDoesNotExistsException(MangroveException):28 def __init__(self, questionnaire_code):29 error_message = u"The questionnaire with code %s does not exist." % questionnaire_code if questionnaire_code else "The questionnaire does not exist."30 MangroveException.__init__(self, error_message, (questionnaire_code, ))31class FieldDoesNotExistsException(MangroveException):32 def __init__(self, field_code):33 MangroveException.__init__(self, u"The field with code %s does not exist." % field_code, (field_code, ))34class EntityQuestionCodeNotSubmitted(MangroveException):35 def __init__(self):36 MangroveException.__init__(self, u"The submission does not contain entity question code.")37class EntityTypeCodeNotSubmitted(MangroveException):38 def __init__(self):39 MangroveException.__init__(self, u"The submission does not contain entity type code.")40class EntityQuestionAlreadyExistsException(MangroveException):41 pass42class QuestionAlreadyExistsException(MangroveException):43 pass44class QuestionnaireAlreadyExistsException(MangroveException):45 pass46class QuestionCodeAlreadyExistsException(MangroveException):47 pass48class NoQuestionsSubmittedException(MangroveException):49 def __init__(self):50 MangroveException.__init__(self, u"The submission contains no valid questions.")51class NumberNotRegisteredException(MangroveException):52 def __init__(self, from_number):53 MangroveException.__init__(self, (u"Sorry, this number %s is not registered with us.") % (from_number,),54 (from_number,))55class MultipleReportersForANumberException(MangroveException):56 def __init__(self, from_number):57 MangroveException.__init__(self,58 (u"Sorry, the telephone number %s has already been registered.") % (from_number,),59 (from_number,))60class MultipleSubmissionsForSameCodeException(MangroveException):61 def __init__(self, field_code):62 MangroveException.__init__(self, (u"Multiple responses for question code %s") % (field_code, ), (field_code,))63class MobileNumberMandatoryException(MangroveException):64 def __init__(self):65 MangroveException.__init__(self, "Answer for question 'Mobile Number' is required")66class EntityTypeDoesNotExistsException(MangroveException):67 def __init__(self, entity_type):68 entity_type_full_name = ".".join(entity_type)69 entity_type_short_name = entity_type[-1]70 MangroveException.__init__(self,71 (u"Entity type %s doesnt exist.") % (entity_type_full_name,),72 (entity_type_short_name,))73class InvalidAnswerSubmissionException(MangroveException):74 def __init__(self, message, code, data=None):75 final_data = [code]76 if data is not None:77 data = [a for a in data]78 final_data.extend(data)79 data = tuple(final_data)80 MangroveException.__init__(self, message, data)81class AnswerTooBigException(InvalidAnswerSubmissionException):82 def __init__(self, code, answer):83 InvalidAnswerSubmissionException.__init__(self,84 (u"Answer %s for question %s is greater than allowed.") % (85 answer, code,), code, (answer,))86class AnswerTooSmallException(InvalidAnswerSubmissionException):87 def __init__(self, code, answer):88 InvalidAnswerSubmissionException.__init__(self,89 (u"Answer %s for question %s is smaller than allowed.") % (90 answer, code), code, (answer,))91class AnswerTooLongException(InvalidAnswerSubmissionException):92 def __init__(self, code, answer, max_length):93 InvalidAnswerSubmissionException.__init__(self,94 (u"Answer %s for question %s is longer than allowed.") % (95 answer, code), code, (answer,))96class AnswerTooShortException(InvalidAnswerSubmissionException):97 def __init__(self, code, answer, min_length):98 InvalidAnswerSubmissionException.__init__(self,99 (u"Answer %s for question %s is shorter than allowed.") % (100 answer, code), code, (answer,))101class AnswerHasTooManyValuesException(InvalidAnswerSubmissionException):102 def __init__(self, code, answer):103 InvalidAnswerSubmissionException.__init__(self,104 (u"Answer %s for question %s contains more than one value.") % (105 answer, code,), code, (answer,))106class AnswerHasNoValuesException(InvalidAnswerSubmissionException):107 def __init__(self, code, answer):108 InvalidAnswerSubmissionException.__init__(self,109 (u"Answer %s for question %s has no value.") % (110 answer, code,), code, (answer,))111class AnswerNotInListException(InvalidAnswerSubmissionException):112 def __init__(self, code, answer):113 InvalidAnswerSubmissionException.__init__(self,114 (115 u"Answer %s for question %s is not present in the allowed options.") % (116 answer, code,), code, (answer,))117class AnswerWrongType(InvalidAnswerSubmissionException):118 def __init__(self, code, answer):119 InvalidAnswerSubmissionException.__init__(self,120 (u"Answer %s for question %s is of the wrong type.") % (answer, code,)121 , code, (answer,))122class IncorrectDate(InvalidAnswerSubmissionException):123 def __init__(self, code, answer, date_format):124 InvalidAnswerSubmissionException.__init__(self,125 (126 u'Answer %s for question %s is invalid. Expected date in %s format') %127 (answer, code, date_format), code, (answer, date_format))128class NoDocumentError(MangroveException):129 pass130class UnknownOrganization(MangroveException):131 def __init__(self, tel_number):132 MangroveException.__init__(self, (u'No organization found for telephone number %s') %133 (tel_number,), (tel_number,))134class ShortCodeAlreadyInUseException(MangroveException):135 def __init__(self, short_code):136 MangroveException.__init__(self, (u'The ID %s is already in use. Please specify another') %137 (short_code,), (short_code,))138class ShortCodeTooLongException(MangroveException):139 def __init__(self):140 MangroveException.__init__(self, u"The short code is longer than 12 characters")141class LatitudeNotFloat(MangroveException):142 def __init__(self, lat):143 MangroveException.__init__(self, (u'Answer must be in the following format: xx.xxxx yy.yyyy Example: -18.1324 27.6547'), data=(lat,))144class LongitudeNotFloat(MangroveException):145 def __init__(self, long):146 MangroveException.__init__(self, (u'Answer must be in the following format: xx.xxxx yy.yyyy Example: -18.1324 27.6547'), data=(long,))147class LongitudeNotInRange(MangroveException):148 def __init__(self, long):149 MangroveException.__init__(self, (u'Invalid GPS value.'), data=(long,))150class LatitudeNotInRange(MangroveException):151 def __init__(self, lat):152 MangroveException.__init__(self, (u'Invalid GPS value.'), (lat,))153class GeoCodeFormatException(MangroveException):154 def __init__(self, data):155 MangroveException.__init__(self,156 u"Incorrect GPS format. The GPS coordinates must be in the following format: xx.xxxx,yy.yyyy. Example -18.8665,47.5315"157 , (data,))158class FailedToSaveDataObject(MangroveException):159 def __init__(self, data):160 MangroveException.__init__(self, u"Root Exception: %s" % data)161class SMSParserInvalidFormatException(MangroveException):162 def __init__(self, data):163 MangroveException.__init__(self, u"Could not parse, invalid format: %s" % data, (data,))164 165class SMSParserWrongNumberOfAnswersException(MangroveException):166 def __init__(self, form_code):167 MangroveException.__init__(self, u"Could not parse, Wrong number of answers submitted.", (form_code, ))168class CSVParserInvalidHeaderFormatException(MangroveException):169 def __init__(self):170 MangroveException.__init__(self, u"Could not parse header, invalid format.")171class XlsParserInvalidHeaderFormatException(MangroveException):172 def __init__(self):173 MangroveException.__init__(self, u"Could not parse header, invalid format.")174class AggregationNotSupportedForTypeException(MangroveException):175 def __init__(self, field, aggregation):176 error_message = "%s for %s is not supported" % (aggregation, field)177 MangroveException.__init__(self, error_message, (aggregation, field))178class SubmissionParseException(MangroveException):179 def __init__(self, form_code, message):180 MangroveException.__init__(self, message, (form_code,))181class MobileNumberMissing(MangroveException):182 def __init__(self):183 MangroveException.__init__(self, "Mobile number is missing", ('reg',))184class RegexMismatchException(MangroveException):185 def __init__(self, pattern):186 MangroveException.__init__(self, "Invalid Mobile Number.")187class ShortCodeRegexMismatchException(MangroveException):188 def __init__(self, pattern):189 MangroveException.__init__(self, "Invalid Short Code. Only letters and numbers are valid.")190class ConstraintTypeUnknownException(MangroveException):191 def __init__(self, name):192 MangroveException.__init__(self, "Unknown constraint type: %s" % (name,))193class RequiredFieldNotPresentException(MangroveException):194 def __init__(self, code):195 MangroveException.__init__(self, "Mandatory Field with code: %s is not present" % (code,))196class LocationFieldNotPresentException(MangroveException):197 def __init__(self):198 MangroveException.__init__(self, "Please fill out atleast one location field")199class AccountExpiredException(MangroveException):200 def __init__(self, message = "Trial account has been expired!"):201 MangroveException.__init__(self, message)202class DeleteRequestParserInvalidFormatException(MangroveException):203 def __init__(self, data):204 MangroveException.__init__(self, u"Could not parse, invalid format: %s" % data, (data,))205class DeleteRequestParserWrongNumberOfAnswersException(MangroveException):206 def __init__(self, message):207 MangroveException.__init__(self, u"Could not parse, Wrong number of answers submitted.", (message, ))208 209class ExceedSubmissionLimitException(MangroveException):210 def __init__(self):211 MangroveException.__init__(self, u"You have reached your limit of 1000 free Submissions. Upgrade to a monthly subscription to continue sending in Submissions.")212class ExceedSMSLimitException(MangroveException):213 def __init__(self):214 MangroveException.__init__(self, u"You have reached your 50 SMS Submission limit. Please upgrade to a monthly subscription to continue sending in SMS Submissions to your Questionnaires.")215class DatasenderIsNotLinkedException(MangroveException):216 def __init__(self, dsname, dsid):217 MangroveException.__init__(self, u"Error. You are not authorized to submit data for this Questionnaire. Please contact your supervisor.", (dsname, dsid))218class CodeSheetMissingException(MangroveException):219 def __init__(self, message="The template you are using is not correct, please use DataWinners template and try again"):...

Full Screen

Full Screen

ExceptionManager.js

Source:ExceptionManager.js Github

copy

Full Screen

1/* Copyright 2016-2019 Firewalla INC2 *3 * This program is free software: you can redistribute it and/or modify4 * it under the terms of the GNU Affero General Public License, version 3,5 * as published by the Free Software Foundation.6 *7 * This program is distributed in the hope that it will be useful,8 * but WITHOUT ANY WARRANTY; without even the implied warranty of9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10 * GNU Affero General Public License for more details.11 *12 * You should have received a copy of the GNU Affero General Public License13 * along with this program. If not, see <http://www.gnu.org/licenses/>.14 */15'use strict';16const log = require('../net2/logger.js')(__filename, 'info');17const minimatch = require('minimatch')18const Exception = require('./Exception.js');19const Bone = require('../lib/Bone.js');20const rclient = require('../util/redis_manager.js').getRedisClient()21let instance = null;22const exceptionQueue = "exception_queue";23const exceptionIDKey = "exception:id";24const initID = 1;25const exceptionPrefix = "exception:";26const flat = require('flat');27const _ = require('lodash');28module.exports = class {29 constructor() {30 if (instance == null) {31 instance = this;32 }33 return instance;34 }35 getExceptionKey(exceptionID) {36 return exceptionPrefix + exceptionID37 }38 getException(exceptionID) {39 return new Promise((resolve, reject) => {40 this.idsToExceptions([exceptionID], (err, results) => {41 if(err) {42 reject(err);43 return;44 }45 if(results == null || results.length === 0) {46 reject(new Error("exception not exists"));47 return;48 }49 resolve(results[0]);50 });51 });52 }53 idsToExceptions(ids, callback) {54 let multi = rclient.multi();55 ids.forEach((eid) => {56 multi.hgetall(exceptionPrefix + eid)57 });58 multi.exec((err, results) => {59 if(err) {60 log.error("Failed to load active exceptions (hgetall): " + err);61 callback(err);62 return;63 }64 callback(null, results.map((r) => this.jsonToException(r)));65 });66 }67 loadExceptionsAsync() {68 return new Promise((resolve, reject) => {69 this.loadExceptions((err, exceptions) => {70 if(err) {71 reject(err)72 } else {73 resolve(exceptions)74 }75 })76 })77 }78 loadExceptions(callback) {79 callback = callback || function() {}80 rclient.smembers(exceptionQueue, (err, results) => {81 if(err) {82 log.error("Fail to load exceptions: " + err);83 callback(err);84 return;85 }86 let multi = rclient.multi();87 results.forEach((eid) => {88 let key = "exception:" + eid;89 multi.hgetall(key);90 });91 multi.exec((err, results) => {92 if(err) {93 log.error("Fail to load exceptions: " + err);94 callback(err);95 }96 results = results.filter((x) => x != null) // ignore any exception which doesn't exist97 let rr = results.map((r) => Object.assign(Object.create(Exception.prototype), r))98 // recent first99 rr.sort((a, b) => {100 return b.timestamp > a.timestamp101 })102 callback(null, rr)103 });104 });105 }106 createExceptionIDKey(callback) {107 rclient.set(exceptionIDKey, initID, callback);108 }109 getNextID(callback) {110 rclient.get(exceptionIDKey, (err, result) => {111 if(err) {112 log.error("Failed to get exceptionIDKey: " + err);113 callback(err);114 return;115 }116 if(result) {117 rclient.incr(exceptionIDKey, (err) => {118 if(err) {119 log.error("Failed to incr exceptionIDKey: " + err);120 }121 callback(null, result);122 });123 } else {124 this.createExceptionIDKey((err) => {125 if(err) {126 log.error("Failed to create exceptionIDKey: " + err);127 callback(err);128 return;129 }130 rclient.incr(exceptionIDKey, (err) => {131 if(err) {132 log.error("Failed to incr exceptionIDKey: " + err);133 }134 callback(null, initID);135 });136 });137 }138 });139 }140 enqueue(exception, callback) {141 let id = exception.eid;142 rclient.sadd(exceptionQueue, id, (err) => {143 if(err) {144 log.error("Failed to add exception to active queue: " + err);145 }146 callback(err);147 });148 }149 getSameExceptions(exception) {150 let em = this151 return new Promise(function (resolve, reject) {152 em.loadExceptions((err, exceptions) => {153 if (err) {154 log.error("failed to load exceptions:", err);155 reject(err)156 } else {157 if (exceptions) {158 resolve(exceptions.filter((e) => e.isEqualToException(exception)))159 } else {160 resolve([])161 }162 }163 })164 })165 }166 async checkAndSave(exception, callback) {167 try {168 let exceptions = await this.getSameExceptions(exception)169 if (exceptions && exceptions.length > 0) {170 log.info(`exception ${exception} already exists in system: ${exceptions}`)171 callback(null, exceptions[0], true)172 } else {173 let ee = await this.saveExceptionAsync(exception)174 callback(null, ee)175 }176 } catch(err) {177 callback(err)178 }179 }180 async checkAndSaveAsync(exception) {181 const exceptions = await this.getSameExceptions(exception);182 if (exceptions && exceptions.length > 0) {183 log.info(`exception ${exception} already exists in system: ${exceptions}`)184 return Promise.reject(new Error("exception already exists"))185 } else {186 return this.saveExceptionAsync(exception);187 }188 }189 saveExceptionAsync(exception) {190 return new Promise((resolve, reject) => {191 this.saveException(exception, (err, ee) => {192 if(err) {193 reject(err)194 } else {195 resolve(ee)196 }197 })198 })199 }200 saveException(exception, callback) {201 callback = callback || function() {}202 this.getNextID((err, id) => {203 if(err) {204 log.error("Failed to get next ID: " + err);205 callback(err);206 return;207 }208 this._saveException(id, exception, callback);209 });210 }211 _saveException(id, exception, callback) {212 exception.eid = id + ""; // convert it to string to make it consistent with redis213 let exceptionKey = exceptionPrefix + id;214 /*215 {216 "i.type": "domain",217 "reason": "ALARM_GAME",218 "type": "ALARM_GAME",219 "timestamp": "1500913117.175",220 "p.dest.id": "battle.net",221 "target_name": "battle.net",222 "target_ip": destIP,223 }*/224 rclient.hmset(exceptionKey, flat.flatten(exception), (err) => {225 if(err) {226 log.error("Failed to set exception: " + err);227 callback(err);228 return;229 }230 this.enqueue(exception, (err) => {231 if(!err) {232// this.publisher.publish("EXCEPTION", "EXCEPTION:CREATED", exception.eid);233 }234 callback(err, exception);235 });236 });237 // ignore is set for backward compatibility, it's actually should be called "allow"238 Bone.submitIntelFeedback('ignore', exception, 'exception');239 }240 exceptionExists(exceptionID) {241 return rclient.existsAsync(exceptionPrefix + exceptionID);242 }243 async deleteException(exceptionID) {244 log.info("Trying to delete exception " + exceptionID);245 if (!exceptionID) return;246 let exists = await this.exceptionExists(exceptionID);247 if(!exists) {248 log.error("exception " + exceptionID + " doesn't exists");249 return;250 }251 let multi = rclient.multi();252 let exception = await rclient.hgetallAsync(exceptionPrefix + exceptionID);253 log.info("Deleting Exception:", exception);254 multi.srem(exceptionQueue, exceptionID);255 multi.del(exceptionPrefix + exceptionID);256 try {257 await multi.execAsync();258 }259 catch(err) {260 log.error("Fail to delete exception: " + err);261 throw err;262 }263 // unignore is set for backward compatibility, it's actually should be called "unallow"264 Bone.submitIntelFeedback('unignore', exception, "exception");265 }266 async deleteExceptions(idList) {267 if (!idList) throw new Error("deleteException: null argument");268 if (idList.length) {269 await rclient.delAsync(idList.map(id => exceptionPrefix + id));270 await rclient.sremAsync(exceptionQueue, idList);271 }272 }273 async deleteMacRelatedExceptions(mac) {274 // remove exceptions275 let exceptions = await this.loadExceptionsAsync();276 let relatedEx = exceptions277 .filter(ex => _.isString(ex['p.device.mac']) &&278 ex['p.device.mac'].toUpperCase() === mac.toUpperCase())279 .map(ex => ex.eid);280 await this.deleteExceptions(relatedEx);281 }282 async createException(json) {283 if(!json) {284 return Promise.reject(new Error("Invalid Exception"));285 }286 if(!json.timestamp) {287 json.timestamp = new Date() / 1000;288 }289 const e = this.jsonToException(json);290 if(e) {291 return this.checkAndSaveAsync(e);292 } else {293 return Promise.reject(new Error("Invalid Exception"));294 }295 }296 async updateException(json) {297 if(!json) {298 return Promise.reject(new Error("Invalid Exception"));299 }300 if (!json.eid) {301 return Promise.reject(new Error("Invalid Exception ID"));302 }303 if(!json.timestamp) {304 json.timestamp = new Date() / 1000;305 }306 const e = this.jsonToException(json);307 if(e) {308 return this.getException(e.eid).then(() => {309 return new Promise((resolve, reject) => {310 this._saveException(e.eid, e, (err, ee) => {311 if(err) {312 reject(err)313 } else {314 resolve(ee)315 }316 })317 })318 });319 } else {320 return Promise.reject(new Error("Invalid Exception"));321 }322 }323 isFirewallaCloud(alarm) {324 const name = alarm["p.dest.name"]325 if(!name) {326 return false327 }328 return name === "firewalla.encipher.io" ||329 name === "firewalla.com" ||330 minimatch(name, "*.firewalla.com")331 // TODO: might need to add static ip address here332 }333 match(alarm, callback) {334 if(this.isFirewallaCloud(alarm)) {335 callback(null, true, [])336 return337 }338 this.loadExceptions((err, results) => {339 if(err) {340 callback(err);341 return;342 }343 let matches = results.filter((e) => e.match(alarm));344 if(matches.length > 0) {345 log.info("Alarm " + alarm.aid + " is covered by exception " + matches.map((e) => e.eid).join(","));346 callback(null, true, matches);347 } else {348 callback(null, false);349 }350 });351 }352 // incr by 1 to count how many times this exception matches alarms353 updateMatchCount(exceptionID) {354 return rclient.hincrbyAsync(this.getExceptionKey(exceptionID), "matchCount", 1)355 }356 createExceptionFromJson(json, callback) {357 callback = callback || function() {}358 callback(null, this.jsonToException(json));359 }360 jsonToException(json) {361 let proto = Exception.prototype;362 if(proto) {363 let obj = Object.assign(Object.create(proto), json);364 return obj;365 } else {366 log.error("Unsupported exception type: " + json.type);367 return null;368 }369 }...

Full Screen

Full Screen

exception.js

Source:exception.js Github

copy

Full Screen

1"use strict";2/**3 * @license4 * Copyright Google LLC All Rights Reserved.5 *6 * Use of this source code is governed by an MIT-style license that can be7 * found in the LICENSE file at https://angular.io/license8 */9Object.defineProperty(exports, "__esModule", { value: true });10exports.UnsupportedPlatformException = exports.UnimplementedException = exports.MergeConflictException = exports.InvalidUpdateRecordException = exports.ContentHasMutatedException = exports.PathIsFileException = exports.PathIsDirectoryException = exports.FileAlreadyExistException = exports.FileDoesNotExistException = exports.UnknownException = exports.BaseException = void 0;11class BaseException extends Error {12 constructor(message = '') {13 super(message);14 }15}16exports.BaseException = BaseException;17class UnknownException extends BaseException {18 constructor(message) {19 super(message);20 }21}22exports.UnknownException = UnknownException;23// Exceptions24class FileDoesNotExistException extends BaseException {25 constructor(path) {26 super(`Path "${path}" does not exist.`);27 }28}29exports.FileDoesNotExistException = FileDoesNotExistException;30class FileAlreadyExistException extends BaseException {31 constructor(path) {32 super(`Path "${path}" already exist.`);33 }34}35exports.FileAlreadyExistException = FileAlreadyExistException;36class PathIsDirectoryException extends BaseException {37 constructor(path) {38 super(`Path "${path}" is a directory.`);39 }40}41exports.PathIsDirectoryException = PathIsDirectoryException;42class PathIsFileException extends BaseException {43 constructor(path) {44 super(`Path "${path}" is a file.`);45 }46}47exports.PathIsFileException = PathIsFileException;48class ContentHasMutatedException extends BaseException {49 constructor(path) {50 super(`Content at path "${path}" has changed between the start and the end of an update.`);51 }52}53exports.ContentHasMutatedException = ContentHasMutatedException;54class InvalidUpdateRecordException extends BaseException {55 constructor() {56 super(`Invalid record instance.`);57 }58}59exports.InvalidUpdateRecordException = InvalidUpdateRecordException;60class MergeConflictException extends BaseException {61 constructor(path) {62 super(`A merge conflicted on path "${path}".`);63 }64}65exports.MergeConflictException = MergeConflictException;66class UnimplementedException extends BaseException {67 constructor() {68 super('This function is unimplemented.');69 }70}71exports.UnimplementedException = UnimplementedException;72class UnsupportedPlatformException extends BaseException {73 constructor() {74 super('This platform is not supported by this code path.');75 }76}...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful