exceptions: Add ValidationFailureError.

This commit is contained in:
PIG208 2021-07-04 16:00:10 +08:00 committed by Tim Abbott
parent a96c614420
commit 43cca07b4b
3 changed files with 19 additions and 6 deletions

View File

@ -1,6 +1,7 @@
from enum import Enum
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Type, TypeVar
from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _
T = TypeVar("T", bound="AbstractEnum")
@ -390,3 +391,14 @@ class AccessDeniedError(JsonableError):
class ResourceNotFoundError(JsonableError):
http_status_code = 404
class ValidationFailureError(JsonableError):
# This class translations a Django ValidationError into a
# Zulip-style JsonableError, sending back just the first error for
# consistency of API.
data_fields = ["errors"]
def __init__(self, error: ValidationError) -> None:
super().__init__(error.messages[0])
self.errors = dict(error)

View File

@ -4,9 +4,9 @@ from django.utils.translation import gettext as _
from zerver.decorator import require_realm_admin
from zerver.lib.actions import do_add_linkifier, do_remove_linkifier, do_update_linkifier
from zerver.lib.exceptions import JsonableError
from zerver.lib.exceptions import JsonableError, ValidationFailureError
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.lib.response import json_success
from zerver.models import RealmFilter, UserProfile, linkifiers_for_realm
@ -32,7 +32,7 @@ def create_linkifier(
)
return json_success({"id": linkifier_id})
except ValidationError as e:
return json_error(e.messages[0], data={"errors": dict(e)})
raise ValidationFailureError(e)
@require_realm_admin
@ -66,4 +66,4 @@ def update_linkifier(
except RealmFilter.DoesNotExist:
raise JsonableError(_("Linkifier not found."))
except ValidationError as e:
return json_error(e.messages[0], data={"errors": dict(e)})
raise ValidationFailureError(e)

View File

@ -6,8 +6,9 @@ from django.utils.translation import gettext as _
from zerver.decorator import require_realm_admin
from zerver.lib.actions import do_add_realm_playground, do_remove_realm_playground
from zerver.lib.exceptions import ValidationFailureError
from zerver.lib.request import REQ, JsonableError, has_request_variables
from zerver.lib.response import json_error, json_success
from zerver.lib.response import json_success
from zerver.lib.validator import check_capped_string, check_url
from zerver.models import Realm, RealmPlayground, UserProfile
@ -50,7 +51,7 @@ def add_realm_playground(
url_prefix=url_prefix.strip(),
)
except ValidationError as e:
return json_error(e.messages[0], data={"errors": dict(e)})
raise ValidationFailureError(e)
return json_success({"id": playground_id})