Analyze a CouchDb response and raises an exception if an error was returned
in the response.
@param response JSON response sent by server
@param errorMessage Message of top exception
@throws Exception If error is returned in response
321054
static public void captureReponseErrors(Object response, String errorMessage) throws Exception {
		if( null == response ) {
			throw new Exception("Capturing errors from null response");
		}
		if( false == (response instanceof JSONObject) ) {
			// Not an error
			return;
		}
		JSONObject obj = (JSONObject)response;
		if( JSONSupport.containsKey(obj,"error") ) {
			String serverMessage;
			try {
				serverMessage = obj.getString("error");
			} catch (Exception e) {
				serverMessage = "Unable to parse error response";
			}
			
			if( null == errorMessage ) {
				errorMessage = "Error returned by database: ";
			}
			throw new Exception(errorMessage+serverMessage);
		}
	}
412973
private static CouchbaseResponse handleOtherResponseMessages(BinaryRequest request, FullBinaryMemcacheResponse msg,
        ResponseStatus status, boolean seqOnMutation, String remoteHostname) {
        CouchbaseResponse response = null;
        ByteBuf content = msg.content();
        long cas = msg.getCAS();
        short statusCode = msg.getStatus();
        String bucket = request.bucket();

        if (request instanceof UnlockRequest) {
            response = new UnlockResponse(status, statusCode, bucket, content, request);
        } else if (request instanceof TouchRequest) {
            response = new TouchResponse(status, statusCode, bucket, content, request);
        } else if (request instanceof AppendRequest) {
            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new AppendResponse(status, statusCode, cas, bucket, content, descr, request);
        } else if (request instanceof PrependRequest) {
            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new PrependResponse(status, statusCode, cas, bucket, content, descr, request);
        } else if (request instanceof KeepAliveRequest) {
            releaseContent(content);
            response = new KeepAliveResponse(status, statusCode, request);
        } else if (request instanceof NoopRequest) {
            releaseContent(content);
            response = new NoopResponse(status, statusCode, request);
        } else if (request instanceof CounterRequest) {
            long value = status.isSuccess() ? content.readLong() : 0;
            releaseContent(content);

            MutationToken descr = extractToken(bucket, seqOnMutation, status.isSuccess(), msg.getExtras(), request.partition());
            response = new CounterResponse(status, statusCode, bucket, value, cas, descr, request);
        } else if (request instanceof StatRequest) {
            String key = null;
            if (msg.getKey() != null) {
                key = new String(msg.getKey(), CHARSET);
            }
            String value = content.toString(CHARSET);
            releaseContent(content);

            response = new StatResponse(status, statusCode, remoteHostname, key, value, bucket, request);
        } else if (request instanceof GetAllMutationTokensRequest) {
            // 2 bytes for partition ID, and 8 bytes for sequence number
            MutationToken[] mutationTokens = new MutationToken[content.readableBytes() / 10];
            for (int i = 0; i < mutationTokens.length; i++) {
                mutationTokens[i] = new MutationToken((long)content.readShort(), 0, content.readLong(), request.bucket());
            }
            releaseContent(content);
            response = new GetAllMutationTokensResponse(mutationTokens, status, statusCode, bucket, request);
        } else if (request instanceof ObserveRequest) {
            byte observed = ObserveResponse.ObserveStatus.UNKNOWN.value();
            long observedCas = 0;
            if (status.isSuccess()) {
                short keyLength = content.getShort(2);
                observed = content.getByte(keyLength + 4);
                observedCas = content.getLong(keyLength + 5);
            }
            releaseContent(content);
            response = new ObserveResponse(status, statusCode, observed, ((ObserveRequest) request).master(),
                    observedCas, bucket, request);
        } else if (request instanceof ObserveSeqnoRequest) {
            if (status.isSuccess()) {
                byte format = content.readByte();
                switch(format) {
                    case 0:
                        response = new NoFailoverObserveSeqnoResponse(
                            ((ObserveSeqnoRequest) request).master(),
                            content.readShort(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            status,
                            statusCode,
                            bucket,
                            request
                        );
                        break;
                    case 1:
                        response = new FailoverObserveSeqnoResponse(
                            ((ObserveSeqnoRequest) request).master(),
                            content.readShort(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            content.readLong(),
                            status,
                            statusCode,
                            bucket,
                            request
                        );
                        break;
                    default:
                        throw new IllegalStateException("Unknown format for observe-seq: " + format);
                }
            } else {
                response = new NoFailoverObserveSeqnoResponse(((ObserveSeqnoRequest) request).master(), (short) 0, 0,
                    0, 0, status, statusCode, bucket, request);
            }
            releaseContent(content);
        }

        return response;
    }
1218241
public static void handleError(HttpResponse response) throws ParseException, IOException {
        log.debug("{}", response.getStatusLine().toString());
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            log.debug("{}", EntityUtils.toString(entity));
        }
    }
398820
def json_error_response(error, response, status_code=400):
    
    msg = {"error": error.error, "error_description": error.explanation}

    response.status_code = status_code
    response.add_header("Content-Type", "application/json")
    response.body = json.dumps(msg)

    return response
1202647
@RequestMapping(value = "/invoke", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseMessage invoke(HttpServletRequest request, HttpServletResponse response) {
        ResponseMessage res = new ResponseMessage();
        try {
            JSONObject json = tgtools.web.util.RequestHelper.parseRequest(request);
            ValidMessage rm = (ValidMessage) tgtools.util.JsonParseHelper.parseToObject(json, ValidMessage.class);

            mUserService.tokenLogin(request.getRemoteAddr(), rm.getUser(), rm.getToken());

            Object obj = restCommand.process(rm.getOperation(), rm.getData());
            res.setStatus(true);
            res.setData(obj);
        } catch (Exception e) {
            res.setStatus(false);
            res.setData(e.getMessage());
        }
        try {
            System.out.println("client结果：" + tgtools.util.JsonParseHelper.parseToJsonObject(res).toString());
        } catch (Exception d) {
        }
        return res;
    }
135225
function (error, type) {

      // don't send a second response
      if (responseHasBeenSent) {
        console.warn('JSON-RPC2 response has already been sent.')
        return
      }
      // notifications should not send error responses (JSON-RPC2 specs)
      if (!isMethodCall) {
        var message = (error && error.toString) ? error.toString() : undefined
        logNotificationResponseWarning(message, requestMessage)
        callback()
        return
      }

      // internals
      var errorObject

      if (error instanceof Error) {
        // serious application error
        console.warn(
          'Error in JSON-RPC2 method ' + methodName + ': ' + error.toString() + '\n'
          + error.stack
        )
        // not sending detailed error info to not expose details about server code
        errorObject = {
          code: errorCodes['APPLICATION_ERROR'],
          message: errorMessages['APPLICATION_ERROR'] + ' (Check server logs for details)'
        }

      } else if (typeof error === 'string') {
        // error message
        errorObject = {
          code: errorCodes[type] || errorCodes['INVALID_REQUEST'],
          message: error
        }

      } else if (typeof error === 'object') {
        if (error.message) {
          // error object
          errorObject = error
          if (error.code === undefined) {
            error.code = errorCodes['INVALID_REQUEST']
          }

        } else {
          // error data
          errorObject = {
            code: errorCodes[type] || errorCodes['INVALID_REQUEST'],
            message: errorMessages[type] || errorMessages['INVALID_REQUEST'],
            data: error
          }
        }

      } else {
        if (error !== undefined) {
          console.warn('Error parameter must be a string (error message) or object (error data)')
        }
        // fallback
        errorObject = errorObjects['INVALID_REQUEST']

      }

      var rpcMessage = {
        jsonrpc: '2.0',
        error: errorObject,
        id: id
      }

      callback(rpcMessage)
      responseHasBeenSent = true

    }
378385
def _catch_index_error(self, response):
        
        code, headers, raw_data = response
        if not raw_data:
            return
        data = json.loads(raw_data)
        if not data or not data.get('errors'):
            return
        try:
            error_dict = data['items'][0]['index']
            message = error_dict['error']
        except (KeyError, IndexError):
            return
        raise exception_response(400, detail=message)
127937
def _assert_response_success(self, response):
        

        if response.status_code != self._STATUS_CODE_OK:
            raise ExceptionFactory.create_exception_for_response(
                response.status_code,
                self._fetch_all_error_message(response),
                self._fetch_response_id(response)
            )
1304345
protected HyperionException readException(Response response) throws IOException
    {
        ErrorResponse errorResponse = null;
        try
        {
            errorResponse = objectMapper.readValue(response.body().byteStream(), ErrorResponse.class);
        }
        catch (Exception ignore)
        {
        }

        HyperionException resolvedException = null;
        if (errorResponse != null)
        {
            try
            {
                Class exceptionClass = Class.forName(errorResponse.getType());
                resolvedException = (HyperionException) exceptionClass.getConstructor(String.class)
                        .newInstance(errorResponse.getMessage());
            }
            catch (Throwable ignore)
            {
            }

            if (resolvedException == null)
            {
                resolvedException =
                        new HyperionException(errorResponse.getStatusCode(), errorResponse.getMessage());
            }

            resolvedException.setErrorDetails(errorResponse.getErrorDetails());
            resolvedException.setErrorTime(errorResponse.getErrorTime());
            resolvedException.setRequestId(errorResponse.getRequestId());
        }

        if (resolvedException == null)
        {
            resolvedException =
                    new HyperionException(response.code(), response.message());
        }

        return resolvedException;

    }
116196
def error(response)
      if (response.content_type || "").include?("json")
        # Attempt to parse the error as JSON
        begin
          json = JSON.parse(response.body)

          if json["errors"] && json["errors"].first
            raise Error::HTTPError.new(json["errors"].first)
          end
        rescue JSON::ParserError; end
      end

      raise Error::HTTPError.new(
        "status"  => response.code,
        "message" => response.body
      )
    end
972088
protected void skipResponseStatusExceptionParsing(String json) throws ResponseErrorJsonParsingException {
    // If this is not an object, it's not an error response.
    if (!json.startsWith("{")) {
      throw new ResponseErrorJsonParsingException();
    }

    int subStrEnd = Math.min(50, json.length());
    if (!json.substring(0, subStrEnd).contains("\"error\"")) {
      throw new ResponseErrorJsonParsingException();
    }
  }
53369
public static void returnStatusResponse(HttpServletResponse response, int status, String message) {
		if (response == null) {
			return;
		}
		PrintWriter out = null;
		try {
			response.setStatus(status);
			response.setContentType(MediaType.APPLICATION_JSON);
			out = response.getWriter();
			ParaObjectUtils.getJsonWriter().writeValue(out, getStatusResponse(Response.Status.
					fromStatusCode(status), message).getEntity());
		} catch (Exception ex) {
			logger.error(null, ex);
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
261039
public void sendError(HttpResponse response,int code,String msg)
    	throws IOException
    {
        Object wrapper = response.getWrapper();
        if (wrapper!=null && wrapper instanceof HttpServletResponse)
            ((HttpServletResponse)wrapper).sendError(code,msg);
        else
            super.sendError(response,code,msg);
    }
126811
private static <T> Func1<List<JsonObject>, Observable<T>> errorsToThrowable(final String messagePrefix) {
        return new Func1<List<JsonObject>, Observable<T>>() {
            @Override
            public Observable<T> call(List<JsonObject> errors) {
                return Observable.<T>error(new CouchbaseException(messagePrefix + errors));
            }
        };
    }
530751
private static JSONObject genError(HttpResponse response) throws JSONException {
    	String code		= response.getFirstHeader("X-Upwork-Error-Code").getValue();
    	String message	= response.getFirstHeader("X-Upwork-Error-Message").getValue();
    	
    	if (code == null) {
    		code = Integer.toString(response.getStatusLine().getStatusCode());
    	}
    	
    	if (message == null) {
    		message = response.getStatusLine().toString();
    	}

    	return new JSONObject("{error: {code: \"" + code + "\", message: \"" + message + "\"}}");
    }
1235095
private function checkWhetherRateLimitHasBeenReached(ResponseInterface $response, $errorMessage)
    {
        $retryAfterHeaders = $response->getHeader('Retry-After');
        if ($response->getStatusCode() === 429 && count($retryAfterHeaders) > 0) {
            $exception = new TooManyRequestsException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode());
            $exception->retryAfterNumberOfSeconds = (int) current($retryAfterHeaders);

            throw $exception;
        }
    }
1319330
public void setResponse(JsonRpcResponse response) {
    if (response.isError()) {
      setException(response.error());
      return;
    }

    try {
      set((V) Messages.fromJson(method.outputBuilder(), response.result()));
    } catch (Exception e) {
      setException(e);
    }
  }