restore http error codes, add some color

This commit is contained in:
Alex Grintsvayg 2017-03-24 17:18:17 -04:00
parent 8fa2524e54
commit c9c84784c9
4 changed files with 39 additions and 21 deletions

View file

@ -11,6 +11,7 @@ at anytime.
### Added ### Added
* Add `wallet_list` command * Add `wallet_list` command
* Add checks for missing/extraneous params when calling jsonrpc commands * Add checks for missing/extraneous params when calling jsonrpc commands
* Added colors to cli error messages
* *
### Changed ### Changed

View file

@ -2,6 +2,7 @@ import argparse
import json import json
import os import os
import sys import sys
import colorama
from lbrynet import conf from lbrynet import conf
from lbrynet.core import utils from lbrynet.core import utils
@ -13,6 +14,7 @@ from httplib import UNAUTHORIZED
def main(): def main():
colorama.init()
parser = argparse.ArgumentParser(add_help=False) parser = argparse.ArgumentParser(add_help=False)
_, arguments = parser.parse_known_args() _, arguments = parser.parse_known_args()
@ -64,7 +66,7 @@ def main():
os.path.basename(sys.argv[0])) os.path.basename(sys.argv[0]))
) )
else: else:
print_help_response(api.call('help', params)) print_help_for_command(api, params['command'])
elif method not in api.commands(): elif method not in api.commands():
print_error("'" + method + "' is not a valid command.") print_error("'" + method + "' is not a valid command.")
@ -77,21 +79,28 @@ def main():
print result print result
else: else:
print utils.json_dumps_pretty(result) print utils.json_dumps_pretty(result)
except (RPCError, KeyError, JSONRPCException) as err: except (RPCError, KeyError, JSONRPCException, HTTPError) as err:
# TODO: The api should return proper error codes error_data = None
# and messages so that they can be passed along to the user if isinstance(err, HTTPError):
# instead of this generic message. error_body = err.read()
# https://app.asana.com/0/158602294500137/200173944358192 try:
print "Something went wrong, here's the usage for %s:" % method error_data = json.loads(error_body)
print_help_response(api.call('help', {'command': method})) except ValueError:
if hasattr(err, 'msg'): print (
print "Here's the traceback for the error you encountered:" "There was an error, and the response was not valid JSON.\n" +
print err.msg "Raw JSONRPC response:\n" + error_body
)
return 1 return 1
print_error(error_data['error']['message'] + "\n", suggest_help=False)
else:
print_error("Something went wrong\n", suggest_help=False)
def print_help_response(help_response): print_help_for_command(api, method)
print help_response['help'] if 'help' in help_response else help_response if 'data' in error_data['error'] and 'traceback' in error_data['error']['data']:
print "Here's the traceback for the error you encountered:"
print "\n".join(error_data['error']['data']['traceback'])
return 1
def parse_params(params): def parse_params(params):
@ -144,7 +153,8 @@ def print_help_suggestion():
def print_error(message, suggest_help=True): def print_error(message, suggest_help=True):
print "ERROR: " + message error_style = colorama.Style.BRIGHT + colorama.Fore.RED
print error_style + "ERROR: " + message + colorama.Style.RESET_ALL
if suggest_help: if suggest_help:
print_help_suggestion() print_help_suggestion()
@ -168,6 +178,14 @@ def print_help(api):
]) ])
def print_help_for_command(api, command):
help_response = api.call('help', {'command': command})
print "Help for %s method:" % command
message = help_response['help'] if 'help' in help_response else help_response
message = "\n".join([' ' + line for line in message.split("\n")])
print message
def wrap_list_to_term_width(l, width=None, separator=', ', prefix=''): def wrap_list_to_term_width(l, width=None, separator=', ', prefix=''):
if width is None: if width is None:
try: try:

View file

@ -44,7 +44,7 @@ class AuthAPIClient(object):
def call(self, method, params={}): def call(self, method, params={}):
self.__id_count += 1 self.__id_count += 1
pre_auth_post_data = { pre_auth_post_data = {
'version': '1.1', 'version': '2',
'method': method, 'method': method,
'params': params, 'params': params,
'id': self.__id_count 'id': self.__id_count

View file

@ -197,11 +197,10 @@ class AuthJSONRPCServer(AuthorizedBase):
response_content = jsonrpc_dumps_pretty(error, id=id_) response_content = jsonrpc_dumps_pretty(error, id=id_)
self._set_headers(request, response_content) self._set_headers(request, response_content)
# TODO: uncomment this after fixing lbrynet-cli to handle error code responses correctly try:
# try: request.setResponseCode(JSONRPCError.HTTP_CODES[error.code])
# request.setResponseCode(JSONRPCError.HTTP_CODES[error.code]) except KeyError:
# except KeyError: request.setResponseCode(JSONRPCError.HTTP_CODES[JSONRPCError.CODE_INTERNAL_ERROR])
# request.setResponseCode(JSONRPCError.HTTP_CODES[JSONRPCError.CODE_INTERNAL_ERROR])
self._render_message(request, response_content) self._render_message(request, response_content)
@staticmethod @staticmethod