Add high-level catching and rename error type

This commit is contained in:
Tim Van Baak 2020-01-29 01:12:53 -08:00
parent 02e7065b21
commit 22d140480d
6 changed files with 39 additions and 27 deletions

View File

@ -8,6 +8,7 @@ import amanuensis.cli as cli
from amanuensis.cli.helpers import ( from amanuensis.cli.helpers import (
USER_ARGS, USER_KWARGS, LEXICON_ARGS, LEXICON_KWARGS) USER_ARGS, USER_KWARGS, LEXICON_ARGS, LEXICON_KWARGS)
import amanuensis.config as config import amanuensis.config as config
from amanuensis.errors import AmanuensisError
def repl(args): def repl(args):
@ -127,7 +128,11 @@ def main(argv):
config.logger.debug(" {}: {}".format(key, val)) config.logger.debug(" {}: {}".format(key, val))
# Execute command. # Execute command.
try:
args.func(args) args.func(args)
except AmanuensisError as e:
config.logger.error('Unexpected internal {}: {}'.format(
type(e).__name__, str(e)))
if __name__ == "__main__": if __name__ == "__main__":
import sys import sys

View File

@ -140,5 +140,5 @@ def command_passwd(args):
args.user.set_password(pw) args.user.set_password(pw)
# Output # Output
logger.info('Updated password for "{}"'.format(args.user.username)) logger.info('Updated password for {}'.format(args.user.username))
return 0 return 0

View File

@ -10,8 +10,8 @@ class MalformedConfigError(AmanuensisError):
class ReadOnlyError(AmanuensisError): class ReadOnlyError(AmanuensisError):
"""A config was edited in readonly mode""" """A config was edited in readonly mode"""
class InternalMisuseError(AmanuensisError): class ArgumentError(AmanuensisError):
"""An internal helper method was called wrongly""" """An internal call was made with invalid arguments"""
class IndexMismatchError(AmanuensisError): class IndexMismatchError(AmanuensisError):
"""An id was obtained from an index, but the object doesn't exist""" """An id was obtained from an index, but the object doesn't exist"""

View File

@ -2,7 +2,7 @@ import os
import time import time
from amanuensis.errors import ( from amanuensis.errors import (
InternalMisuseError, IndexMismatchError, MissingConfigError) ArgumentError, IndexMismatchError, MissingConfigError)
from amanuensis.config import prepend, json_ro, json_rw from amanuensis.config import prepend, json_ro, json_rw
class LexiconModel(): class LexiconModel():
@ -16,10 +16,10 @@ class LexiconModel():
the lexicon's config, raises an error. the lexicon's config, raises an error.
""" """
if lid and name: if lid and name:
raise InternalMisuseError("lid and name both specified to Lexicon" raise ArgumentError("lid and name both specified to Lexicon"
"Model.by()") "Model.by()")
if not lid and not name: if not lid and not name:
raise ValueError("One of lid or name must be not None") raise ArgumentError("One of lid or name must be not None")
if not lid: if not lid:
with json_ro('lexicon', 'index.json') as index: with json_ro('lexicon', 'index.json') as index:
lid = index.get(name) lid = index.get(name)

View File

@ -11,6 +11,7 @@ import uuid
from amanuensis.config import prepend, json_rw, json_ro, logger from amanuensis.config import prepend, json_rw, json_ro, logger
from amanuensis.config.loader import AttrOrderedDict from amanuensis.config.loader import AttrOrderedDict
from amanuensis.errors import ArgumentError
from amanuensis.lexicon import LexiconModel from amanuensis.lexicon import LexiconModel
from amanuensis.resources import get_stream from amanuensis.resources import get_stream
@ -19,7 +20,7 @@ def valid_name(name):
Validates that a lexicon name consists only of alpahnumerics, dashes, Validates that a lexicon name consists only of alpahnumerics, dashes,
underscores, and spaces underscores, and spaces
""" """
return name is not None and re.match(r"^[A-Za-z0-9-_ ]+$", name) is not None return re.match(r"^[A-Za-z0-9-_ ]+$", name) is not None
def create_lexicon(name, editor): def create_lexicon(name, editor):
@ -27,10 +28,16 @@ def create_lexicon(name, editor):
Creates a lexicon with the given name and sets the given user as its editor Creates a lexicon with the given name and sets the given user as its editor
""" """
# Verify arguments # Verify arguments
if not name:
raise ArgumentError('Empty lexicon name: "{}"'.format(name))
if not valid_name(name): if not valid_name(name):
raise ValueError("Invalid lexicon name: '{}'".format(name)) raise ArgumentError('Invalid lexicon name: "{}"'.format(name))
with json_ro('lexicon', 'index.json') as index:
if name in index.keys():
raise ArgumentError('Lexicon name already taken: "{}"'.format(
name))
if editor is None: if editor is None:
raise ValueError("Invalid editor: '{}'".format(editor)) raise ArgumentError("Invalid editor: '{}'".format(editor))
# Create the lexicon directory and initialize it with a blank lexicon # Create the lexicon directory and initialize it with a blank lexicon
lid = uuid.uuid4().hex lid = uuid.uuid4().hex
@ -79,7 +86,7 @@ def delete_lexicon(lex, purge=False):
""" """
# Verify arguments # Verify arguments
if lex is None: if lex is None:
raise ValueError("Invalid lexicon: '{}'".format(lex)) raise ArgumentError("Invalid lexicon: '{}'".format(lex))
# Delete the lexicon from the index # Delete the lexicon from the index
with json_rw('lexicon', 'index.json') as j: with json_rw('lexicon', 'index.json') as j:
@ -140,9 +147,9 @@ def add_player(lex, player):
""" """
# Verify arguments # Verify arguments
if lex is None: if lex is None:
raise ValueError("Invalid lexicon: '{}'".format(lex)) raise ArgumentError("Invalid lexicon: '{}'".format(lex))
if player is None: if player is None:
raise ValueError("Invalid player: '{}'".format(player)) raise ArgumentError("Invalid player: '{}'".format(player))
# Idempotently add player # Idempotently add player
added = False added = False
@ -162,11 +169,11 @@ def remove_player(lex, player):
""" """
# Verify arguments # Verify arguments
if lex is None: if lex is None:
raise ValueError("Invalid lexicon: '{}'".format(lex)) raise ArgumentError("Invalid lexicon: '{}'".format(lex))
if player is None: if player is None:
raise ValueError("Invalid player: '{}'".format(player)) raise ArgumentError("Invalid player: '{}'".format(player))
if lex.editor == player.id: if lex.editor == player.id:
raise ValueError( raise ArgumentError(
"Can't remove the editor '{}' from lexicon '{}'".format( "Can't remove the editor '{}' from lexicon '{}'".format(
player.username, lex.name)) player.username, lex.name))
@ -186,16 +193,16 @@ def add_character(lex, player, charinfo={}):
""" """
# Verify arguments # Verify arguments
if lex is None: if lex is None:
raise ValueError("Invalid lexicon: '{}'".format(lex)) raise ArgumentError("Invalid lexicon: '{}'".format(lex))
if player is None: if player is None:
raise ValueError("Invalid player: '{}'".format(player)) raise ArgumentError("Invalid player: '{}'".format(player))
if not charinfo or not charinfo.get("name"): if not charinfo or not charinfo.get("name"):
raise ValueError("Invalid character info: '{}'".format(charinfo)) raise ArgumentError("Invalid character info: '{}'".format(charinfo))
charname = charinfo.get("name") charname = charinfo.get("name")
if any([ if any([
char.name for char in lex.character.values() char.name for char in lex.character.values()
if char.name == charname]): if char.name == charname]):
raise ValueError("Duplicate character name: '{}'".format(charinfo)) raise ArgumentError("Duplicate character name: '{}'".format(charinfo))
# Load the character template # Load the character template
with get_stream('character.json') as template: with get_stream('character.json') as template:
@ -223,16 +230,16 @@ def delete_character(lex, charname):
""" """
# Verify arguments # Verify arguments
if lex is None: if lex is None:
raise ValueError("Invalid lexicon: '{}'".format(lex)) raise ArgumentError("Invalid lexicon: '{}'".format(lex))
if charname is None: if charname is None:
raise ValueError("Invalid character name: '{}'".format(charname)) raise ArgumentError("Invalid character name: '{}'".format(charname))
# Find character in this lexicon # Find character in this lexicon
matches = [ matches = [
char for cid, char in lex.character.items() char for cid, char in lex.character.items()
if char.name == charname] if char.name == charname]
if len(matches) != 1: if len(matches) != 1:
raise ValueError(matches) raise ArgumentError(matches)
char = matches[0] char = matches[0]
# Remove character from character list # Remove character from character list

View File

@ -7,7 +7,7 @@ from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash from werkzeug.security import generate_password_hash, check_password_hash
from amanuensis.errors import ( from amanuensis.errors import (
InternalMisuseError, MissingConfigError, IndexMismatchError) ArgumentError, MissingConfigError, IndexMismatchError)
from amanuensis.config import prepend, json_ro, json_rw from amanuensis.config import prepend, json_ro, json_rw
from amanuensis.resources import get_stream from amanuensis.resources import get_stream
from amanuensis.lexicon.manage import get_all_lexicons from amanuensis.lexicon.manage import get_all_lexicons
@ -23,9 +23,9 @@ class UserModel(UserMixin):
the user's config, raises an error. the user's config, raises an error.
""" """
if uid and name: if uid and name:
raise InternalMisuseError("uid and name both specified to UserModel.by()") raise ArgumentError("uid and name both specified to UserModel.by()")
if not uid and not name: if not uid and not name:
raise ValueError("One of uid or name must be not None") raise ArgumentError("One of uid or name must be not None")
if not uid: if not uid:
with json_ro('user', 'index.json') as index: with json_ro('user', 'index.json') as index:
uid = index.get(name) uid = index.get(name)