How to use getResponseForJsonwpError method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

errors.js

Source:errors.js Github

copy

Full Screen

1import ES6Error from 'es6-error';2import _ from 'lodash';3import { util, logger } from 'appium-support';4import { StatusCodes as HTTPStatusCodes } from 'http-status-codes';5const mjsonwpLog = logger.getLogger('MJSONWP');6const w3cLog = logger.getLogger('W3C');7const W3C_UNKNOWN_ERROR = 'unknown error';8// base error class for all of our errors9class ProtocolError extends ES6Error {10  constructor (msg, jsonwpCode, w3cStatus, error) {11    super(msg);12    this.jsonwpCode = jsonwpCode;13    this.error = error || W3C_UNKNOWN_ERROR;14    if (this.jsonwpCode === null) {15      this.jsonwpCode = 13;16    }17    this.w3cStatus = w3cStatus || HTTPStatusCodes.BAD_REQUEST;18    this._stacktrace = null;19  }20  get stacktrace () {21    return this._stacktrace || this.stack;22  }23  set stacktrace (value) {24    this._stacktrace = value;25  }26}27// https://github.com/SeleniumHQ/selenium/blob/176b4a9e3082ac1926f2a436eb346760c37a5998/java/client/src/org/openqa/selenium/remote/ErrorCodes.java#L21528// https://github.com/SeleniumHQ/selenium/issues/5562#issuecomment-37037947029// https://w3c.github.io/webdriver/webdriver-spec.html#dfn-error-code30class NoSuchDriverError extends ProtocolError {31  static code () {32    return 6;33  }34  // W3C Error is called InvalidSessionID35  static w3cStatus () {36    return HTTPStatusCodes.NOT_FOUND;37  }38  static error () {39    return 'invalid session id';40  }41  constructor (err) {42    super(err || 'A session is either terminated or not started', NoSuchDriverError.code(),43          NoSuchDriverError.w3cStatus(), NoSuchDriverError.error());44  }45}46class NoSuchElementError extends ProtocolError {47  static code () {48    return 7;49  }50  static w3cStatus () {51    return HTTPStatusCodes.NOT_FOUND;52  }53  static error () {54    return 'no such element';55  }56  constructor (err) {57    super(err || 'An element could not be located on the page using the given ' +58          'search parameters.', NoSuchElementError.code(), NoSuchElementError.w3cStatus(),59          NoSuchElementError.error());60  }61}62class NoSuchFrameError extends ProtocolError {63  static code () {64    return 8;65  }66  static error () {67    return 'no such frame';68  }69  static w3cStatus () {70    return HTTPStatusCodes.NOT_FOUND;71  }72  constructor (err) {73    super(err || 'A request to switch to a frame could not be satisfied because ' +74          'the frame could not be found.', NoSuchFrameError.code(),75          NoSuchFrameError.w3cStatus(), NoSuchFrameError.error());76  }77}78class UnknownCommandError extends ProtocolError {79  static code () {80    return 9;81  }82  static w3cStatus () {83    return HTTPStatusCodes.NOT_FOUND;84  }85  static error () {86    return 'unknown command';87  }88  constructor (err) {89    super(err || 'The requested resource could not be found, or a request was ' +90          'received using an HTTP method that is not supported by the mapped ' +91          'resource.', UnknownCommandError.code(), UnknownCommandError.w3cStatus(), UnknownCommandError.error());92  }93}94class StaleElementReferenceError extends ProtocolError {95  static code () {96    return 10;97  }98  static w3cStatus () {99    return HTTPStatusCodes.NOT_FOUND;100  }101  static error () {102    return 'stale element reference';103  }104  constructor (err) {105    super(err || 'An element command failed because the referenced element is no ' +106          'longer attached to the DOM.', StaleElementReferenceError.code(),107          StaleElementReferenceError.w3cStatus(), StaleElementReferenceError.error());108  }109}110class ElementNotVisibleError extends ProtocolError {111  static code () {112    return 11;113  }114  static w3cStatus () {115    return HTTPStatusCodes.BAD_REQUEST;116  }117  static error () {118    return 'element not visible';119  }120  constructor (err) {121    super(err || 'An element command could not be completed because the element is ' +122          'not visible on the page.', ElementNotVisibleError.code(),123          ElementNotVisibleError.w3cStatus(), ElementNotVisibleError.error());124  }125}126class InvalidElementStateError extends ProtocolError {127  static code () {128    return 12;129  }130  static w3cStatus () {131    return HTTPStatusCodes.BAD_REQUEST;132  }133  static error () {134    return 'invalid element state';135  }136  constructor (err) {137    super(err || 'An element command could not be completed because the element is ' +138          'in an invalid state (e.g. attempting to click a disabled element).',139          InvalidElementStateError.code(), InvalidElementStateError.w3cStatus(),140          InvalidElementStateError.error());141  }142}143class UnknownError extends ProtocolError {144  static code () {145    return 13;146  }147  static w3cStatus () {148    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;149  }150  static error () {151    return W3C_UNKNOWN_ERROR;152  }153  constructor (errorOrMessage) {154    const origMessage = _.isString((errorOrMessage || {}).message)155      ? errorOrMessage.message156      : errorOrMessage;157    const message = 'An unknown server-side error occurred while processing the command.' +158      (origMessage ? ` Original error: ${origMessage}` : '');159    super(message, UnknownError.code(), UnknownError.w3cStatus(), UnknownError.error());160  }161}162class UnknownMethodError extends ProtocolError {163  static code () {164    return 405;165  }166  static w3cStatus () {167    return HTTPStatusCodes.METHOD_NOT_ALLOWED;168  }169  static error () {170    return 'unknown method';171  }172  constructor (err) {173    super(err || 'The requested command matched a known URL but did not match an method for that URL',174          UnknownMethodError.code(), UnknownMethodError.w3cStatus(), UnknownMethodError.error());175  }176}177class UnsupportedOperationError extends ProtocolError {178  static code () {179    return 405;180  }181  static w3cStatus () {182    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;183  }184  static error () {185    return 'unsupported operation';186  }187  constructor (err) {188    super(err || 'A server-side error occurred. Command cannot be supported.',189          UnsupportedOperationError.code(), UnsupportedOperationError.w3cStatus(),190          UnsupportedOperationError.error());191  }192}193class ElementIsNotSelectableError extends ProtocolError {194  static code () {195    return 15;196  }197  static error () {198    return 'element not selectable';199  }200  static w3cStatus () {201    return HTTPStatusCodes.BAD_REQUEST;202  }203  constructor (err) {204    super(err || 'An attempt was made to select an element that cannot be selected.',205          ElementIsNotSelectableError.code(), ElementIsNotSelectableError.w3cStatus(),206          ElementIsNotSelectableError.error());207  }208}209class ElementClickInterceptedError extends ProtocolError {210  static code () {211    return 64;212  }213  static error () {214    return 'element click intercepted';215  }216  static w3cStatus () {217    return HTTPStatusCodes.BAD_REQUEST;218  }219  constructor (err) {220    super(err || 'The Element Click command could not be completed because the element receiving ' +221          'the events is obscuring the element that was requested clicked',222          ElementClickInterceptedError.code(), ElementClickInterceptedError.w3cStatus(),223          ElementClickInterceptedError.error());224  }225}226class ElementNotInteractableError extends ProtocolError {227  static code () {228    return 60;229  }230  static error () {231    return 'element not interactable';232  }233  static w3cStatus () {234    return HTTPStatusCodes.BAD_REQUEST;235  }236  constructor (err) {237    super(err || 'A command could not be completed because the element is not pointer- or keyboard interactable',238          ElementNotInteractableError.code(), ElementNotInteractableError.w3cStatus(),239          ElementNotInteractableError.error());240  }241}242class InsecureCertificateError extends ProtocolError {243  static error () {244    return 'insecure certificate';245  }246  constructor (err) {247    super(err || 'Navigation caused the user agent to hit a certificate warning, which is usually the result of an expired or invalid TLS certificate',248      ElementIsNotSelectableError.code(), null, InsecureCertificateError.error());249  }250}251class JavaScriptError extends ProtocolError {252  static code () {253    return 17;254  }255  static w3cStatus () {256    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;257  }258  static error () {259    return 'javascript error';260  }261  constructor (err) {262    super(err || 'An error occurred while executing user supplied JavaScript.',263          JavaScriptError.code(), JavaScriptError.w3cStatus(), JavaScriptError.error());264  }265}266class XPathLookupError extends ProtocolError {267  static code () {268    return 19;269  }270  static w3cStatus () {271    return HTTPStatusCodes.BAD_REQUEST;272  }273  static error () {274    return 'invalid selector';275  }276  constructor (err) {277    super(err || 'An error occurred while searching for an element by XPath.',278          XPathLookupError.code(), XPathLookupError.w3cStatus(), XPathLookupError.error());279  }280}281class TimeoutError extends ProtocolError {282  static code () {283    return 21;284  }285  static w3cStatus () {286    return HTTPStatusCodes.REQUEST_TIMEOUT;287  }288  static error () {289    return 'timeout';290  }291  constructor (err) {292    super(err || 'An operation did not complete before its timeout expired.',293          TimeoutError.code(), TimeoutError.w3cStatus(), TimeoutError.error());294  }295}296class NoSuchWindowError extends ProtocolError {297  static code () {298    return 23;299  }300  static error () {301    return 'no such window';302  }303  static w3cStatus () {304    return HTTPStatusCodes.NOT_FOUND;305  }306  constructor (err) {307    super(err || 'A request to switch to a different window could not be satisfied ' +308          'because the window could not be found.', NoSuchWindowError.code(),309          NoSuchWindowError.w3cStatus(), NoSuchWindowError.error());310  }311}312class InvalidArgumentError extends ProtocolError {313  static code () {314    return 61;315  }316  static error () {317    return 'invalid argument';318  }319  static w3cStatus () {320    return HTTPStatusCodes.BAD_REQUEST;321  }322  constructor (err) {323    super(err || 'The arguments passed to the command are either invalid or malformed',324          InvalidArgumentError.code(), InvalidArgumentError.w3cStatus(),325          InvalidArgumentError.error());326  }327}328class InvalidCookieDomainError extends ProtocolError {329  static code () {330    return 24;331  }332  static error () {333    return 'invalid cookie domain';334  }335  static w3cStatus () {336    return HTTPStatusCodes.BAD_REQUEST;337  }338  constructor (err) {339    super(err || 'An illegal attempt was made to set a cookie under a different ' +340          'domain than the current page.', InvalidCookieDomainError.code(),341          InvalidCookieDomainError.w3cStatus(), InvalidCookieDomainError.error());342  }343}344class NoSuchCookieError extends ProtocolError {345  static code () {346    return 62;347  }348  static w3cStatus () {349    return HTTPStatusCodes.NOT_FOUND;350  }351  static error () {352    return 'no such cookie';353  }354  constructor (err) {355    super(err || 'No cookie matching the given path name was found amongst the associated cookies of the current browsing context’s active document',356          NoSuchCookieError.code(), NoSuchCookieError.w3cStatus(), NoSuchCookieError.error());357  }358}359class UnableToSetCookieError extends ProtocolError {360  static code () {361    return 25;362  }363  static w3cStatus () {364    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;365  }366  static error () {367    return 'unable to set cookie';368  }369  constructor (err) {370    super(err || 'A request to set a cookie\'s value could not be satisfied.',371          UnableToSetCookieError.code(), UnableToSetCookieError.w3cStatus(), UnableToSetCookieError.error());372  }373}374class UnexpectedAlertOpenError extends ProtocolError {375  static code () {376    return 26;377  }378  static w3cStatus () {379    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;380  }381  static error () {382    return 'unexpected alert open';383  }384  constructor (err) {385    super(err || 'A modal dialog was open, blocking this operation',386          UnexpectedAlertOpenError.code(), UnexpectedAlertOpenError.w3cStatus(), UnexpectedAlertOpenError.error());387  }388}389class NoAlertOpenError extends ProtocolError {390  static code () {391    return 27;392  }393  static w3cStatus () {394    return HTTPStatusCodes.NOT_FOUND;395  }396  static error () {397    return 'no such alert';398  }399  constructor (err) {400    super(err || 'An attempt was made to operate on a modal dialog when one ' +401          'was not open.', NoAlertOpenError.code(), NoAlertOpenError.w3cStatus(), NoAlertOpenError.error());402  }403}404class NoSuchAlertError extends NoAlertOpenError {}405class ScriptTimeoutError extends ProtocolError {406  static code () {407    return 28;408  }409  static w3cStatus () {410    return HTTPStatusCodes.REQUEST_TIMEOUT;411  }412  static error () {413    return 'script timeout';414  }415  constructor (err) {416    super(err || 'A script did not complete before its timeout expired.',417          ScriptTimeoutError.code(), ScriptTimeoutError.w3cStatus(), ScriptTimeoutError.error());418  }419}420class InvalidElementCoordinatesError extends ProtocolError {421  static code () {422    return 29;423  }424  static w3cStatus () {425    return HTTPStatusCodes.BAD_REQUEST;426  }427  static error () {428    return 'invalid coordinates';429  }430  constructor (err) {431    super(err || 'The coordinates provided to an interactions operation are invalid.',432          InvalidElementCoordinatesError.code(), InvalidElementCoordinatesError.w3cStatus(),433          InvalidElementCoordinatesError.error());434  }435}436class InvalidCoordinatesError extends InvalidElementCoordinatesError {}437class IMENotAvailableError extends ProtocolError {438  static code () {439    return 30;440  }441  static w3cStatus () {442    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;443  }444  static error () {445    return 'unsupported operation';446  }447  constructor (err) {448    super(err || 'IME was not available.', IMENotAvailableError.code(),449          IMENotAvailableError.w3cStatus(), IMENotAvailableError.error());450  }451}452class IMEEngineActivationFailedError extends ProtocolError {453  static code () {454    return 31;455  }456  static w3cStatus () {457    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;458  }459  static error () {460    return 'unsupported operation';461  }462  constructor (err) {463    super(err || 'An IME engine could not be started.',464          IMEEngineActivationFailedError.code(), IMEEngineActivationFailedError.w3cStatus(),465          IMEEngineActivationFailedError.error());466  }467}468class InvalidSelectorError extends ProtocolError {469  static code () {470    return 32;471  }472  static w3cStatus () {473    return HTTPStatusCodes.BAD_REQUEST;474  }475  static error () {476    return 'invalid selector';477  }478  constructor (err) {479    super(err || 'Argument was an invalid selector (e.g. XPath/CSS).',480          InvalidSelectorError.code(), InvalidSelectorError.w3cStatus(),481          InvalidSelectorError.error());482  }483}484class SessionNotCreatedError extends ProtocolError {485  static code () {486    return 33;487  }488  static w3cStatus () {489    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;490  }491  static error () {492    return 'session not created';493  }494  constructor (details) {495    let message = 'A new session could not be created.';496    if (details) {497      message += ` Details: ${details}`;498    }499    super(message, SessionNotCreatedError.code(), SessionNotCreatedError.w3cStatus(), SessionNotCreatedError.error());500  }501}502class MoveTargetOutOfBoundsError extends ProtocolError {503  static code () {504    return 34;505  }506  static w3cStatus () {507    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;508  }509  static error () {510    return 'move target out of bounds';511  }512  constructor (err) {513    super(err || 'Target provided for a move action is out of bounds.',514          MoveTargetOutOfBoundsError.code(), MoveTargetOutOfBoundsError.w3cStatus(), MoveTargetOutOfBoundsError.error());515  }516}517class NoSuchContextError extends ProtocolError {518  static code () {519    return 35;520  }521  constructor (err) {522    super(err || 'No such context found.', NoSuchContextError.code());523  }524}525class InvalidContextError extends ProtocolError {526  static code () {527    return 36;528  }529  constructor (err) {530    super(err || 'That command could not be executed in the current context.',531          InvalidContextError.code());532  }533}534// These are aliases for UnknownMethodError535class NotYetImplementedError extends UnknownMethodError {536  constructor (err) {537    super(err || 'Method has not yet been implemented');538  }539}540class NotImplementedError extends UnknownMethodError {541  constructor (err) {542    super(err || 'Method is not implemented');543  }544}545class UnableToCaptureScreen extends ProtocolError {546  static code () {547    return 63;548  }549  static w3cStatus () {550    return HTTPStatusCodes.INTERNAL_SERVER_ERROR;551  }552  static error () {553    return 'unable to capture screen';554  }555  constructor (err) {556    super(err || 'A screen capture was made impossible',557          UnableToCaptureScreen.code(), UnableToCaptureScreen.w3cStatus(), UnableToCaptureScreen.error());558  }559}560// Equivalent to W3C InvalidArgumentError561class BadParametersError extends ES6Error {562  static error () {563    return 'invalid argument';564  }565  constructor (requiredParams, actualParams, errMessage) {566    let message;567    if (!errMessage) {568      message = `Parameters were incorrect. We wanted ` +569          `${JSON.stringify(requiredParams)} and you ` +570          `sent ${JSON.stringify(actualParams)}`;571    } else {572      message = `Parameters were incorrect. You sent ${JSON.stringify(actualParams)}, ${errMessage}`;573    }574    super(message);575    this.w3cStatus = HTTPStatusCodes.BAD_REQUEST;576  }577}578/**579 * ProxyRequestError is a custom error and will be thrown up on unsuccessful proxy request and580 * will contain information about the proxy failure.581 * In case of ProxyRequestError should fetch the actual error by calling `getActualError()`582 * for proxy failure to generate the client response.583 */584class ProxyRequestError extends ES6Error {585  constructor (err, responseError, httpStatus) {586    let responseErrorObj = util.safeJsonParse(responseError);587    if (!_.isPlainObject(responseErrorObj)) {588      responseErrorObj = {};589    }590    let origMessage = _.isString(responseError) ? responseError : '';591    if (!_.isEmpty(responseErrorObj)) {592      if (_.isString(responseErrorObj.value)) {593        origMessage = responseErrorObj.value;594      } else if (_.isPlainObject(responseErrorObj.value) && _.isString(responseErrorObj.value.message)) {595        origMessage = responseErrorObj.value.message;596      }597    }598    super(_.isEmpty(err) ? `Proxy request unsuccessful. ${origMessage}` : err);599    this.w3cStatus = HTTPStatusCodes.BAD_REQUEST;600    // If the response error is an object and value is an object, it's a W3C error (for JSONWP value is a string)601    if (_.isPlainObject(responseErrorObj.value) && _.has(responseErrorObj.value, 'error')) {602      this.w3c = responseErrorObj.value;603      this.w3cStatus = httpStatus || HTTPStatusCodes.BAD_REQUEST;604    } else {605      this.jsonwp = responseErrorObj;606    }607  }608  getActualError () {609    // If it's MJSONWP error, returns actual error cause for request failure based on `jsonwp.status`610    if (util.hasValue(this.jsonwp) && util.hasValue(this.jsonwp.status) && util.hasValue(this.jsonwp.value)) {611      return errorFromMJSONWPStatusCode(this.jsonwp.status, this.jsonwp.value);612    } else if (util.hasValue(this.w3c) && _.isNumber(this.w3cStatus) && this.w3cStatus >= 300) {613      return errorFromW3CJsonCode(this.w3c.error, this.w3c.message || this.message, this.w3c.stacktrace);614    }615    return new UnknownError(this.message);616  }617}618// map of error class name to error class619const errors = {NotYetImplementedError,620                NotImplementedError,621                BadParametersError,622                InvalidArgumentError,623                NoSuchDriverError,624                NoSuchElementError,625                UnknownCommandError,626                StaleElementReferenceError,627                ElementNotVisibleError,628                InvalidElementStateError,629                UnknownError,630                ElementIsNotSelectableError,631                ElementClickInterceptedError,632                ElementNotInteractableError,633                InsecureCertificateError,634                JavaScriptError,635                XPathLookupError,636                TimeoutError,637                NoSuchWindowError,638                NoSuchCookieError,639                InvalidCookieDomainError,640                InvalidCoordinatesError,641                UnableToSetCookieError,642                UnexpectedAlertOpenError,643                NoAlertOpenError,644                ScriptTimeoutError,645                InvalidElementCoordinatesError,646                IMENotAvailableError,647                IMEEngineActivationFailedError,648                InvalidSelectorError,649                SessionNotCreatedError,650                MoveTargetOutOfBoundsError,651                NoSuchAlertError,652                NoSuchContextError,653                InvalidContextError,654                NoSuchFrameError,655                UnableToCaptureScreen,656                UnknownMethodError,657                UnsupportedOperationError,658                ProxyRequestError};659// map of error code to error class660const jsonwpErrorCodeMap = {};661for (let ErrorClass of _.values(errors)) {662  if (ErrorClass.code) {663    jsonwpErrorCodeMap[ErrorClass.code()] = ErrorClass;664  }665}666const w3cErrorCodeMap = {};667for (let ErrorClass of _.values(errors)) {668  if (ErrorClass.error) {669    w3cErrorCodeMap[ErrorClass.error()] = ErrorClass;670  }671}672function isUnknownError (err) {673  return !err.constructor.name ||674         !_.values(errors).find(function equalNames (error) {675           return error.name === err.constructor.name;676         });677}678function isErrorType (err, type) {679  // `name` property is the constructor name680  if (type.name === ProtocolError.name) {681    // `jsonwpCode` is `0` on success682    return !!err.jsonwpCode;683  } else if (type.name === ProxyRequestError.name) {684    // `status` is `0` on success685    if (err.jsonwp) {686      return !!err.jsonwp.status;687    }688    if (_.isPlainObject(err.w3c)) {689      return _.isNumber(err.w3cStatus) && err.w3cStatus >= 300;690    }691    return false;692  }693  return err.constructor.name === type.name;694}695/**696 * Retrieve an error derived from MJSONWP status697 * @param {number} code JSONWP status code698 * @param {string|Object} value The error message, or an object with a `message` property699 * @return {ProtocolError} The error that is associated with provided JSONWP status code700 */701function errorFromMJSONWPStatusCode (code, value = '') {702  // if `value` is an object, pull message from it, otherwise use the plain703  // value, or default to an empty string, if null704  const message = (value || {}).message || value || '';705  if (code !== UnknownError.code() && jsonwpErrorCodeMap[code]) {706    mjsonwpLog.debug(`Matched JSONWP error code ${code} to ${jsonwpErrorCodeMap[code].name}`);707    return new jsonwpErrorCodeMap[code](message);708  }709  mjsonwpLog.debug(`Matched JSONWP error code ${code} to UnknownError`);710  return new UnknownError(message);711}712/**713 * Retrieve an error derived from W3C JSON Code714 * @param {string} code W3C error string (see https://www.w3.org/TR/webdriver/#handling-errors `JSON Error Code` column)715 * @param {string} message the error message716 * @param {?string} stacktrace an optional error stacktrace717 * @return {ProtocolError}  The error that is associated with the W3C error string718 */719function errorFromW3CJsonCode (code, message, stacktrace = null) {720  if (code && w3cErrorCodeMap[code.toLowerCase()]) {721    w3cLog.debug(`Matched W3C error code '${code}' to ${w3cErrorCodeMap[code.toLowerCase()].name}`);722    const resultError = new w3cErrorCodeMap[code.toLowerCase()](message);723    resultError.stacktrace = stacktrace;724    return resultError;725  }726  w3cLog.debug(`Matched W3C error code '${code}' to UnknownError`);727  const resultError = new UnknownError(message);728  resultError.stacktrace = stacktrace;729  return resultError;730}731/**732 * Convert an Appium error to proper W3C HTTP response733 * @param {ProtocolError} err The error that needs to be translated734 */735function getResponseForW3CError (err) {736  let httpStatus;737  // W3C defined error message (https://www.w3.org/TR/webdriver/#dfn-error-code)738  let w3cErrorString;739  if (!err.w3cStatus) {740    err = util.hasValue(err.status)741      // If it's a JSONWP error, find corresponding error742      ? errorFromMJSONWPStatusCode(err.status, err.value)743      : new errors.UnknownError(err.message);744  }745  if (isErrorType(err, errors.BadParametersError)) {746    // respond with a 400 if we have bad parameters747    w3cLog.debug(`Bad parameters: ${err}`);748    w3cErrorString = BadParametersError.error();749  } else {750    w3cErrorString = err.error;751  }752  httpStatus = err.w3cStatus;753  if (!w3cErrorString) {754    w3cErrorString = UnknownError.error();755  }756  let httpResBody = {757    value: {758      error: w3cErrorString,759      message: err.message,760      stacktrace: err.stacktrace || err.stack,761    }762  };763  return [httpStatus, httpResBody];764}765/**766 * Convert an Appium error to a proper JSONWP response767 * @param {ProtocolError} err The error to be converted768 */769function getResponseForJsonwpError (err) {770  if (isUnknownError(err)) {771    err = new errors.UnknownError(err);772  }773  // MJSONWP errors are usually 500 status code so set it to that by default774  let httpStatus = HTTPStatusCodes.INTERNAL_SERVER_ERROR;775  let httpResBody = {776    status: err.jsonwpCode,777    value: {778      message: err.message779    }780  };781  if (isErrorType(err, errors.BadParametersError)) {782    // respond with a 400 if we have bad parameters783    mjsonwpLog.debug(`Bad parameters: ${err}`);784    httpStatus = HTTPStatusCodes.BAD_REQUEST;785    httpResBody = err.message;786  } else if (isErrorType(err, errors.NotYetImplementedError) ||787             isErrorType(err, errors.NotImplementedError)) {788    // respond with a 501 if the method is not implemented789    httpStatus = HTTPStatusCodes.NOT_IMPLEMENTED;790  } else if (isErrorType(err, errors.NoSuchDriverError)) {791    // respond with a 404 if there is no driver for the session792    httpStatus = HTTPStatusCodes.NOT_FOUND;793  }794  return [httpStatus, httpResBody];795}796export {797  ProtocolError, errors, isErrorType, isUnknownError,798  errorFromMJSONWPStatusCode, errorFromW3CJsonCode,799  getResponseForW3CError, getResponseForJsonwpError,...

Full Screen

Full Screen

protocol.js

Source:protocol.js Github

copy

Full Screen

...331      }332      if (currentProtocol === PROTOCOLS.W3C) {333        [httpStatus, httpResBody] = getResponseForW3CError(actualErr);334      } else if (currentProtocol === PROTOCOLS.MJSONWP) {335        [httpStatus, httpResBody] = getResponseForJsonwpError(actualErr);336      } else {337        // If it's unknown what the protocol is (like if it's `getStatus` prior to `createSession`), merge the responses338        // together to be protocol-agnostic339        let jsonwpRes = getResponseForJsonwpError(actualErr);340        let w3cRes = getResponseForW3CError(actualErr);341        httpResBody = {342          ...jsonwpRes[1],343          ...w3cRes[1],344        };345        // Use the JSONWP status code (which is usually 500)346        httpStatus = jsonwpRes[0];347      }348    }349    // decode the response, which is either a string or json350    if (_.isString(httpResBody)) {351      res.status(httpStatus).send(httpResBody);352    } else {353      if (newSessionId) {...

Full Screen

Full Screen

mjsonwp.js

Source:mjsonwp.js Github

copy

Full Screen

...223        actualErr = new errors.UnknownError(err);224      }225      // if anything goes wrong, figure out what our response should be226      // based on the type of error that we encountered227      [httpStatus, httpResBody] = getResponseForJsonwpError(actualErr);228    }229    // decode the response, which is either a string or json230    if (_.isString(httpResBody)) {231      res.status(httpStatus).send(httpResBody);232    } else {233      if (newSessionId) {234        httpResBody.sessionId = newSessionId;235      } else {236        httpResBody.sessionId = req.params.sessionId || null;237      }238      res.status(httpStatus).json(httpResBody);239    }240  };241  // add the method to the app...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const appiumBaseDriver = require('appium-base-driver');2const { getResponseForJsonwpError } = appiumBaseDriver;3const { getResponseForW3CError } = appiumBaseDriver;4const appiumBaseDriver = require('appium-base-driver');5const { getResponseForJsonwpError } = appiumBaseDriver;6const { getResponseForW3CError } = appiumBaseDriver;7const appiumBaseDriver = require('appium-base-driver');8const { getResponseForJsonwpError } = appiumBaseDriver;9const { getResponseForW3CError } = appiumBaseDriver;10const appiumBaseDriver = require('appium-base-driver');11const { getResponseForJsonwpError } = appiumBaseDriver;12const { getResponseForW3CError } = appiumBaseDriver;13const appiumBaseDriver = require('appium-base-driver');14const { getResponseForJsonwpError } = appiumBaseDriver;15const { getResponseForW3CError } = appiumBaseDriver;16const appiumBaseDriver = require('appium-base-driver');17const { getResponseForJsonwpError } = appiumBaseDriver;18const { getResponseForW3CError } = appiumBaseDriver;19const appiumBaseDriver = require('appium-base-driver');20const { getResponseForJsonwpError } = app

Full Screen

Using AI Code Generation

copy

Full Screen

1const appiumBaseDriver = require('appium-base-driver');2const { getResponseForJsonwpError } = appiumBaseDriver;3const appiumBaseDriver = require('appium-base-driver');4const { getResponseForJsonwpError } = appiumBaseDriver;5const appiumBaseDriver = require('appium-base-driver');6const { getResponseForJsonwpError } = appiumBaseDriver;7const appiumBaseDriver = require('appium-base-driver');8const { getResponseForJsonwpError } = appiumBaseDriver;9const appiumBaseDriver = require('appium-base-driver');10const { getResponseForJsonwpError } = appiumBaseDriver;11const appiumBaseDriver = require('appium-base-driver');12const { getResponseForJsonwpError } = appiumBaseDriver;13const appiumBaseDriver = require('appium-base-driver');14const { getResponseForJsonwpError } = appiumBaseDriver;15const appiumBaseDriver = require('appium-base-driver');16const { getResponseForJsonwpError } = appiumBaseDriver;17const appiumBaseDriver = require('appium-base-driver');18const { getResponseForJsonwpError } = appiumBaseDriver;19const appiumBaseDriver = require('appium-base-driver');20const { getResponseForJsonwpError } = appiumBaseDriver;21const appiumBaseDriver = require('appium-base-driver');22const { getResponseForJsonwpError } = appiumBaseDriver;

Full Screen

Using AI Code Generation

copy

Full Screen

1const BaseDriver = require('appium-base-driver');2const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');3const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');4const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');5const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');6const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');7const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');8const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');9const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');10const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');11const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');12const { getResponseForJsonwpError } = require('appium-base-driver/build/lib/mjsonwp/errors');13const { getResponseForW3CError } = require('appium-base-driver/build/lib/protocol/errors');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getResponseForJsonwpError } = require('appium-base-driver').errors;2const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;3const { getResponseForJsonwpError } = require('appium-base-driver').errors;4const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;5const { getResponseForJsonwpError } = require('appium-base-driver').errors;6const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;7const { getResponseForJsonwpError } = require('appium-base-driver').errors;8const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;9const { getResponseForJsonwpError } = require('appium-base-driver').errors;10const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;11const { getResponseForJsonwpError } = require('appium-base-driver').errors;12const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;13const { getResponseForJsonwpError } = require('appium-base-driver').errors;14const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;15const { getResponseForJsonwpError } = require('appium-base-driver').errors;16const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;17const { getResponseForJsonwpError } = require('appium-base-driver').errors;18const { errorFromMJSONWPStatusCode } = require('appium-base-driver').protocol;19const { get

Full Screen

Using AI Code Generation

copy

Full Screen

1var appiumBaseDriver = require('appium-base-driver');2var baseDriver = new appiumBaseDriver.Basedriver();3var error = new Error('Error');4var response = baseDriver.getResponseForJsonwpError(error);5console.log(response);6{7  value: {8    stacktrace: 'Error: Error\n    at Object.<anonymous> (/Users/username/Desktop/test.js:7:17)\n    at Module._compile (internal/modules/cjs/loader.js:1137:30)\n    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)\n    at Module.load (internal/modules/cjs/loader.js:985:32)\n    at Function.Module._load (internal/modules/cjs/loader.js:878:14)\n    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)\n    at internal/main/run_main_module.js:17:47'9  }10}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getResponseForJsonwpError } = require('appium-base-driver');2const { errors } = require('appium-base-driver');3const { MJSONWPError } = errors;4const error = new MJSONWPError('Invalid Argument', 400, 'Invalid Argument');5const status = getResponseForJsonwpError(error);6console.log(status);7{ status: 400,8  value: '{"status":400,"value":{"message":"Invalid Argument","error":"Invalid Argument"}}' }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { getResponseForJsonwpError } = require('appium-base-driver').protocol;2const { errors } = require('appium-base-driver');3const { MJSONWP } = errors;4const jsonwpError = new MJSONWP.InvalidSelectorError("Invalid selector");5const response = getResponseForJsonwpError(jsonwpError);6console.log(response);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { AppiumBaseDriver } = require('appium-base-driver');2let response = AppiumBaseDriver.getResponseForJsonwpError(error);3console.log(response);4{ status: 13,5   { error: 'unknown error',6     stacktrace: '' } }

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 Appium Base Driver 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