Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add error codes for Saleor errors

Aleksander Spyraf918f9f4041c
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index e5e9924893..1c516e0917 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -2,6 +2,7 @@ from collections import defaultdict
import i18naddress
from django import forms
+from django.core.exceptions import ValidationError
from django.forms.forms import BoundField
from django.utils.translation import pgettext_lazy
from django_countries import countries
@@ -178,7 +179,7 @@ class CountryAwareAddressForm(AddressForm):
error_msg = pgettext_lazy(
"Address form", "This value is invalid for selected country"
)
- self.add_error(field, error_msg)
+ self.add_error(field, ValidationError(error_msg, code=error_code))
def validate_address(self, data):
try:
diff --git a/saleor/account/validators.py b/saleor/account/validators.py
index 4bfcb0ad8f..70045e6b2a 100644
--- a/saleor/account/validators.py
+++ b/saleor/account/validators.py
@@ -3,6 +3,8 @@ from django.utils.translation import ugettext_lazy as _
from phonenumber_field.phonenumber import to_python
from phonenumbers.phonenumberutil import is_possible_number
+from ..graphql.core.utils.error_codes import AccountErrorCode
+
def validate_possible_number(phone, country=None):
phone_number = to_python(phone, country)
@@ -12,6 +14,7 @@ def validate_possible_number(phone, country=None):
or not phone_number.is_valid()
):
raise ValidationError(
- _("The phone number entered is not valid."), code="invalid_phone_number"
+ _("The phone number entered is not valid."),
+ code=AccountErrorCode.INVALID_PHONE_NUMBER,
)
return phone_number
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 23feed7dfe..3aa894774d 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -39,6 +39,7 @@ from ..giftcard.utils import (
add_gift_card_code_to_checkout,
remove_gift_card_code_from_checkout,
)
+from ..graphql.core.utils.error_codes import CheckoutErrorCode
from ..order import events
from ..order.emails import send_order_confirmation
from ..order.models import Order, OrderLine
@@ -828,7 +829,12 @@ def add_voucher_code_to_checkout(checkout: Checkout, voucher_code: str, discount
add_voucher_to_checkout(checkout, voucher, discounts)
except NotApplicable:
raise ValidationError(
- {"promo_code": "Voucher is not applicable to that checkout."}
+ {
+ "promo_code": ValidationError(
+ "Voucher is not applicable to that checkout.",
+ code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ )
+ }
)
@@ -1191,18 +1197,28 @@ def clean_checkout(checkout: Checkout, discounts):
"""Check if checkout can be completed."""
if checkout.is_shipping_required():
if not checkout.shipping_method:
- raise ValidationError("Shipping method is not set")
+ raise ValidationError(
+ "Shipping method is not set",
+ code=CheckoutErrorCode.SHIPPING_METHOD_NOT_SET,
+ )
if not checkout.shipping_address:
- raise ValidationError("Shipping address is not set")
+ raise ValidationError(
+ "Shipping address is not set",
+ code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET,
+ )
if not is_valid_shipping_method(checkout, discounts):
raise ValidationError(
- "Shipping method is not valid for your shipping address"
+ "Shipping method is not valid for your shipping address",
+ code=CheckoutErrorCode.INVALID_SHIPPING_METHOD,
)
if not checkout.billing_address:
- raise ValidationError("Billing address is not set")
+ raise ValidationError(
+ "Billing address is not set", code=CheckoutErrorCode.BILLING_ADDRESS_NOT_SET
+ )
if not is_fully_paid(checkout, discounts):
raise ValidationError(
- "Provided payment methods can not cover the checkout's total " "amount"
+ "Provided payment methods can not cover the checkout's total " "amount",
+ code=CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID,
)
diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.py
index 46d6958d18..4df630603e 100644
--- a/saleor/core/exceptions.py
+++ b/saleor/core/exceptions.py
@@ -1,4 +1,8 @@
+from ..graphql.core.utils.error_codes import CheckoutErrorCode
+
+
class InsufficientStock(Exception):
def __init__(self, item):
super().__init__("Insufficient stock for %r" % (item,))
self.item = item
+ self.code = CheckoutErrorCode.INSUFFICIENT_STOCK
diff --git a/saleor/core/utils/url.py b/saleor/core/utils/url.py
index 7913c92306..a00e8a4673 100644
--- a/saleor/core/utils/url.py
+++ b/saleor/core/utils/url.py
@@ -4,6 +4,8 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.http.request import split_domain_port, validate_host
+from ...graphql.core.utils.error_codes import CommonErrorCode
+
def validate_storefront_url(url):
"""Validate the storefront URL.
@@ -15,10 +17,14 @@ def validate_storefront_url(url):
parsed_url = urlparse(url)
domain, _ = split_domain_port(parsed_url.netloc)
except ValueError as error:
- raise ValidationError({"redirectUrl": str(error)})
+ raise ValidationError(
+ {"redirectUrl": str(error)}, code=CommonErrorCode.INVALID_STOREFRONT_URL
+ )
if not validate_host(domain, settings.ALLOWED_CLIENT_HOSTS):
error_message = (
f"{domain or url} is not allowed. Please check "
"`ALLOWED_CLIENT_HOSTS` configuration."
)
- raise ValidationError({"redirectUrl": error_message})
+ raise ValidationError(
+ {"redirectUrl": error_message}, code=CommonErrorCode.INVALID_STOREFRONT_URL
+ )
diff --git a/saleor/graphql/account/bulk_mutations.py b/saleor/graphql/account/bulk_mutations.py
index 53636971f2..631ea4cd1a 100644
--- a/saleor/graphql/account/bulk_mutations.py
+++ b/saleor/graphql/account/bulk_mutations.py
@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationError
from ...account import models
from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation
+from ..core.utils.error_codes import AccountErrorCode
from .utils import CustomerDeleteMixin, StaffDeleteMixin
@@ -54,11 +55,21 @@ class UserBulkSetActive(BaseBulkMutation):
def clean_instance(cls, info, instance):
if info.context.user == instance:
raise ValidationError(
- {"is_active": "Cannot activate or deactivate your own account."}
+ {
+ "is_active": ValidationError(
+ "Cannot activate or deactivate your own account.",
+ code=AccountErrorCode.ACTIVATE_OWN_ACCOUNT,
+ )
+ }
)
elif instance.is_superuser:
raise ValidationError(
- {"is_active": "Cannot activate or deactivate superuser's account."}
+ {
+ "is_active": ValidationError(
+ "Cannot activate or deactivate superuser's account.",
+ code=AccountErrorCode.ACTIVATE_SUPERUSER_ACCOUNT,
+ )
+ }
)
@classmethod
diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.py
index 65c102db42..3b38389994 100644
--- a/saleor/graphql/account/i18n.py
+++ b/saleor/graphql/account/i18n.py
@@ -4,6 +4,7 @@ from django_countries import countries
from ...account.forms import get_address_form
from ...account.models import Address
from ...account.validators import validate_possible_number
+from ..core.utils.error_codes import AccountErrorCode
class I18nMixin:
@@ -20,17 +21,27 @@ class I18nMixin:
validate_possible_number(phone, address_data.get("country"))
except ValidationError as exc:
raise ValidationError(
- {"phone": f"'{phone}' is not a valid phone number."}
+ {
+ "phone": ValidationError(
+ f"'{phone}' is not a valid phone number.", code=exc.code
+ )
+ }
) from exc
country_code = address_data.get("country")
if country_code in countries.countries.keys():
address_form, _ = get_address_form(address_data, address_data["country"])
else:
- raise ValidationError({"country": "Invalid country code."})
+ raise ValidationError(
+ {
+ "country": ValidationError(
+ "Invalid country code.", code=AccountErrorCode.INVALID_COUNTRY
+ )
+ }
+ )
if not address_form.is_valid():
- raise ValidationError(address_form.errors)
+ raise ValidationError(address_form.errors.as_data())
if not instance:
instance = Address()
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 93b6022179..cce53a8b52 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -8,6 +8,7 @@ from ....core.utils.url import validate_storefront_url
from ...account.enums import AddressTypeEnum
from ...account.types import Address, AddressInput, User
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ...core.utils.error_codes import AccountErrorCode
from .base import (
INVALID_TOKEN,
BaseAddressDelete,
@@ -124,7 +125,10 @@ class AccountDelete(ModelDeleteMutation):
def clean_instance(cls, info, instance):
super().clean_instance(info, instance)
if instance.is_staff:
- raise ValidationError("Cannot delete a staff account.")
+ raise ValidationError(
+ "Cannot delete a staff account.",
+ code=AccountErrorCode.DELETE_STUFF_ACCOUNT,
+ )
@classmethod
def perform_mutation(cls, _root, info, **data):
@@ -133,7 +137,13 @@ class AccountDelete(ModelDeleteMutation):
token = data.pop("token")
if not default_token_generator.check_token(user, token):
- raise ValidationError({"token": INVALID_TOKEN})
+ raise ValidationError(
+ {
+ "token": ValidationError(
+ INVALID_TOKEN, code=AccountErrorCode.INVALID_USER_TOKEN
+ )
+ }
+ )
db_id = user.id
@@ -222,7 +232,14 @@ class AccountSetDefaultAddress(BaseMutation):
user = info.context.user
if not user.addresses.filter(pk=address.pk).exists():
- raise ValidationError({"id": "The address doesn't belong to that user."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "The address doesn't belong to that user.",
+ code=AccountErrorCode.NOT_USERS_ADDRESS,
+ )
+ }
+ )
if data.get("type") == AddressTypeEnum.BILLING.value:
address_type = AddressType.BILLING
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index d0a9c7d8c1..6801267969 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -20,6 +20,7 @@ from ...core.mutations import (
UpdateMetaBaseMutation,
validation_error_to_error_type,
)
+from ...core.utils.error_codes import AccountErrorCode
BILLING_ADDRESS_FIELD = "default_billing_address"
SHIPPING_ADDRESS_FIELD = "default_shipping_address"
@@ -71,13 +72,25 @@ class SetPassword(CreateToken):
try:
user = models.User.objects.get(email=email)
except ObjectDoesNotExist:
- raise ValidationError({"email": "User doesn't exist"})
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "User doesn't exist", code=AccountErrorCode.USER_DOES_NOT_EXIST
+ )
+ }
+ )
if not default_token_generator.check_token(user, token):
- raise ValidationError({"token": INVALID_TOKEN})
+ raise ValidationError(
+ {
+ "token": ValidationError(
+ INVALID_TOKEN, code=AccountErrorCode.INVALID_USER_TOKEN
+ )
+ }
+ )
try:
password_validation.validate_password(password, user)
except ValidationError as error:
- raise ValidationError({"password": error.messages})
+ raise ValidationError({"password": error})
user.set_password(password)
user.save(update_fields=["password"])
account_events.customer_password_reset_event(user=user)
@@ -109,7 +122,14 @@ class RequestPasswordReset(BaseMutation):
try:
user = models.User.objects.get(email=email)
except ObjectDoesNotExist:
- raise ValidationError({"email": "User with this email doesn't exist"})
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "User with this email doesn't exist",
+ code=AccountErrorCode.USER_DOES_NOT_EXIST,
+ )
+ }
+ )
send_user_password_reset_email_with_url(redirect_url, user)
return RequestPasswordReset()
diff --git a/saleor/graphql/account/mutations/deprecated_account.py b/saleor/graphql/account/mutations/deprecated_account.py
index b35c63f258..2782ae61c3 100644
--- a/saleor/graphql/account/mutations/deprecated_account.py
+++ b/saleor/graphql/account/mutations/deprecated_account.py
@@ -6,6 +6,7 @@ from ....checkout import AddressType
from ...account.enums import AddressTypeEnum
from ...account.types import Address, AddressInput, User
from ...core.mutations import BaseMutation, ModelMutation
+from ...core.utils.error_codes import AccountErrorCode
from .base import BaseCustomerCreate, UserAddressInput
from .deprecated_staff import send_user_password_reset_email
@@ -137,7 +138,14 @@ class CustomerSetDefaultAddress(BaseMutation):
user = info.context.user
if address not in user.addresses.all():
- raise ValidationError({"id": "The address doesn't belong to that user."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "The address doesn't belong to that user.",
+ code=AccountErrorCode.NOT_USERS_ADDRESS,
+ )
+ }
+ )
if data.get("type") == AddressTypeEnum.BILLING.value:
address_type = AddressType.BILLING
@@ -173,7 +181,14 @@ class CustomerPasswordReset(BaseMutation):
try:
user = models.User.objects.get(email=email)
except ObjectDoesNotExist:
- raise ValidationError({"email": "User with this email doesn't exist"})
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "User with this email doesn't exist",
+ code=AccountErrorCode.USER_DOES_NOT_EXIST,
+ )
+ }
+ )
site = info.context.site
send_user_password_reset_email(user, site)
return CustomerPasswordReset()
diff --git a/saleor/graphql/account/mutations/deprecated_staff.py b/saleor/graphql/account/mutations/deprecated_staff.py
index 9095635647..70dcc144fc 100644
--- a/saleor/graphql/account/mutations/deprecated_staff.py
+++ b/saleor/graphql/account/mutations/deprecated_staff.py
@@ -7,6 +7,7 @@ from django.utils.http import urlsafe_base64_encode
from ....account import emails, models
from ...core.mutations import BaseMutation
+from ...core.utils.error_codes import AccountErrorCode
def send_user_password_reset_email(user, site):
@@ -37,7 +38,14 @@ class PasswordReset(BaseMutation):
try:
user = models.User.objects.get(email=email)
except ObjectDoesNotExist:
- raise ValidationError({"email": "User with this email doesn't exist"})
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "User with this email doesn't exist",
+ code=AccountErrorCode.USER_DOES_NOT_EXIST,
+ )
+ }
+ )
site = info.context.site
send_user_password_reset_email(user, site)
return PasswordReset()
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index f71628db5d..b27bd3dd3a 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -25,6 +25,7 @@ from ...core.mutations import (
)
from ...core.types import Upload
from ...core.utils import validate_image_file
+from ...core.utils.error_codes import AccountErrorCode
from ..utils import CustomerDeleteMixin, StaffDeleteMixin, UserDeleteMixin
from .base import (
BaseAddressDelete,
@@ -210,11 +211,21 @@ class StaffUpdate(StaffCreate):
if not is_active:
if user == instance:
raise ValidationError(
- {"is_active": "Cannot deactivate your own account."}
+ {
+ "is_active": ValidationError(
+ "Cannot deactivate your own account.",
+ code=AccountErrorCode.DEACTIVATE_OWN_ACCOUNT,
+ )
+ }
)
elif instance.is_superuser:
raise ValidationError(
- {"is_active": "Cannot deactivate superuser's account."}
+ {
+ "is_active": ValidationError(
+ "Cannot deactivate superuser's account.",
+ code=AccountErrorCode.DEACTIVATE_SUPERUSER_ACCOUNT,
+ )
+ }
)
@classmethod
@@ -318,7 +329,12 @@ class AddressSetDefault(BaseMutation):
if not user.addresses.filter(pk=address.pk).exists():
raise ValidationError(
- {"address_id": "The address doesn't belong to that user."}
+ {
+ "address_id": ValidationError(
+ "The address doesn't belong to that user.",
+ code=AccountErrorCode.NOT_USERS_ADDRESS,
+ )
+ }
)
if data.get("type") == AddressTypeEnum.BILLING.value:
diff --git a/saleor/graphql/account/utils.py b/saleor/graphql/account/utils.py
index 941adb6bb9..3e44d10cd4 100644
--- a/saleor/graphql/account/utils.py
+++ b/saleor/graphql/account/utils.py
@@ -2,6 +2,7 @@ from django.core.exceptions import ValidationError
from graphene.utils.str_converters import to_camel_case
from ...account import events as account_events
+from ..core.utils.error_codes import AccountErrorCode
class UserDeleteMixin:
@@ -12,9 +13,23 @@ class UserDeleteMixin:
def clean_instance(cls, info, instance):
user = info.context.user
if instance == user:
- raise ValidationError({"id": "You cannot delete your own account."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "You cannot delete your own account.",
+ code=AccountErrorCode.DELETE_OWN_ACCOUNT,
+ )
+ }
+ )
elif instance.is_superuser:
- raise ValidationError({"id": "Cannot delete this account."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot delete this account.",
+ code=AccountErrorCode.DELETE_SUPERUSER_ACCOUNT,
+ )
+ }
+ )
class CustomerDeleteMixin(UserDeleteMixin):
@@ -25,7 +40,14 @@ class CustomerDeleteMixin(UserDeleteMixin):
def clean_instance(cls, info, instance):
super().clean_instance(info, instance)
if instance.is_staff:
- raise ValidationError({"id": "Cannot delete a staff account."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot delete a staff account.",
+ code=AccountErrorCode.DELETE_STAFF_ACCOUNT,
+ )
+ }
+ )
@classmethod
def post_process(cls, info, deleted_count=1):
@@ -42,7 +64,14 @@ class StaffDeleteMixin(UserDeleteMixin):
def clean_instance(cls, info, instance):
super().clean_instance(info, instance)
if not instance.is_staff:
- raise ValidationError({"id": "Cannot delete a non-staff user."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot delete a non-staff user.",
+ code=AccountErrorCode.DELETE_NON_STAFF_USER,
+ )
+ }
+ )
def get_required_fields_camel_case(required_fields: set) -> set:
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 4dcfbe60cc..57d129309c 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -41,6 +41,7 @@ from ..core.mutations import (
UpdateMetaBaseMutation,
)
from ..core.utils import from_global_id_strict_type
+from ..core.utils.error_codes import CheckoutErrorCode, CommonErrorCode
from ..order.types import Order
from ..product.types import ProductVariant
from ..shipping.types import ShippingMethod
@@ -59,12 +60,16 @@ def clean_shipping_method(
return True
if not checkout.is_shipping_required():
- raise ValidationError("This checkout does not requires shipping.")
+ raise ValidationError(
+ "This checkout does not requires shipping.",
+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED,
+ )
if not checkout.shipping_address:
raise ValidationError(
"Cannot choose a shipping method for a checkout without the "
- "shipping address."
+ "shipping address.",
+ code=CheckoutErrorCode.SHIPPING_ADDRESS_NOT_SET,
)
valid_methods = get_valid_shipping_methods_for_checkout(checkout, discounts)
@@ -89,13 +94,21 @@ def check_lines_quantity(variants, quantities):
for variant, quantity in zip(variants, quantities):
if quantity < 1:
raise ValidationError(
- {"quantity": "The quantity should be higher than zero."}
+ {
+ "quantity": ValidationError(
+ "The quantity should be higher than zero.",
+ code=CommonErrorCode.POSITIVE_NUMBER_REQUIRED,
+ )
+ }
)
if quantity > settings.MAX_CHECKOUT_LINE_QUANTITY:
raise ValidationError(
{
- "quantity": "Cannot add more than %d times this item."
- "" % settings.MAX_CHECKOUT_LINE_QUANTITY
+ "quantity": ValidationError(
+ "Cannot add more than %d times this item."
+ "" % settings.MAX_CHECKOUT_LINE_QUANTITY,
+ code=CheckoutErrorCode.QUANTITY_GREATER_THAN_LIMIT,
+ )
}
)
try:
@@ -109,7 +122,7 @@ def check_lines_quantity(variants, quantities):
"item_name": e.item.display_product(),
}
)
- raise ValidationError({"quantity": message})
+ raise ValidationError({"quantity": ValidationError(message, code=e.code)})
class CheckoutLineInput(graphene.InputObjectType):
@@ -249,7 +262,9 @@ class CheckoutCreate(ModelMutation, I18nMixin):
try:
add_variant_to_checkout(instance, variant, quantity)
except InsufficientStock as exc:
- raise ValidationError(f"Insufficient product stock: {exc.item}")
+ raise ValidationError(
+ f"Insufficient product stock: {exc.item}", code=exc.code
+ )
# Save provided addresses and associate them to the checkout
cls.save_addresses(instance, cleaned_input)
@@ -317,7 +332,9 @@ class CheckoutLinesAdd(BaseMutation):
checkout, variant, quantity, replace=replace
)
except InsufficientStock as exc:
- raise ValidationError(f"Insufficient product stock: {exc.item}")
+ raise ValidationError(
+ f"Insufficient product stock: {exc.item}", code=exc.code
+ )
recalculate_checkout_discount(checkout, info.context.discounts)
@@ -428,11 +445,23 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
).get(pk=pk)
except ObjectDoesNotExist:
raise ValidationError(
- {"checkout_id": f"Couldn't resolve to a node: {checkout_id}"}
+ {
+ "checkout_id": ValidationError(
+ f"Couldn't resolve to a node: {checkout_id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
if not checkout.is_shipping_required():
- raise ValidationError({"shipping_address": ERROR_DOES_NOT_SHIP})
+ raise ValidationError(
+ {
+ "shipping_address": ValidationError(
+ ERROR_DOES_NOT_SHIP,
+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED,
+ )
+ }
+ )
shipping_address = cls.validate_address(
shipping_address, instance=checkout.shipping_address
@@ -520,11 +549,23 @@ class CheckoutShippingMethodUpdate(BaseMutation):
).get(pk=pk)
except ObjectDoesNotExist:
raise ValidationError(
- {"checkout_id": f"Couldn't resolve to a node: {checkout_id}"}
+ {
+ "checkout_id": ValidationError(
+ f"Couldn't resolve to a node: {checkout_id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
if not checkout.is_shipping_required():
- raise ValidationError({"shipping_method": ERROR_DOES_NOT_SHIP})
+ raise ValidationError(
+ {
+ "shipping_method": ValidationError(
+ ERROR_DOES_NOT_SHIP,
+ code=CheckoutErrorCode.SHIPPING_NOT_REQUIRED,
+ )
+ }
+ )
shipping_method = cls.get_node_or_error(
info,
@@ -539,7 +580,12 @@ class CheckoutShippingMethodUpdate(BaseMutation):
if not shipping_method_is_valid:
raise ValidationError(
- {"shipping_method": "This shipping method is not applicable."}
+ {
+ "shipping_method": ValidationError(
+ "This shipping method is not applicable.",
+ code=CheckoutErrorCode.SHIPPING_METHOD_NOT_APPLICABLE,
+ )
+ }
)
checkout.shipping_method = shipping_method
@@ -587,12 +633,18 @@ class CheckoutComplete(BaseMutation):
discounts=info.context.discounts,
)
except InsufficientStock as e:
- raise ValidationError(f"Insufficient product stock: {e.item}")
+ raise ValidationError(
+ f"Insufficient product stock: {e.item}", code=e.code
+ )
except voucher_model.NotApplicable:
- raise ValidationError("Voucher not applicable")
+ raise ValidationError(
+ "Voucher not applicable",
+ code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ )
except TaxError as tax_error:
return ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error)
+ "Unable to calculate taxes - %s" % str(tax_error),
+ code=CheckoutErrorCode.TAX_ERROR,
)
billing_address = order_data["billing_address"]
@@ -617,7 +669,7 @@ class CheckoutComplete(BaseMutation):
except PaymentError as e:
abort_order_data(order_data)
- raise ValidationError(str(e))
+ raise ValidationError(str(e), code=CommonErrorCode.PAYMENT_ERROR)
if txn.customer_id and user.is_authenticated:
store_customer_id(user, payment.gateway, txn.customer_id)
@@ -659,14 +711,24 @@ class CheckoutUpdateVoucher(BaseMutation):
)
except voucher_model.Voucher.DoesNotExist:
raise ValidationError(
- {"voucher_code": "Voucher with given code does not exist."}
+ {
+ "voucher_code": ValidationError(
+ "Voucher with given code does not exist.",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
try:
add_voucher_to_checkout(checkout, voucher)
except voucher_model.NotApplicable:
raise ValidationError(
- {"voucher_code": "Voucher is not applicable to that checkout."}
+ {
+ "voucher_code": ValidationError(
+ "Voucher is not applicable to that checkout.",
+ code=CheckoutErrorCode.VOUCHER_NOT_APPLICABLE,
+ )
+ }
)
else:
existing_voucher = get_voucher_for_checkout(checkout)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index b9c044396b..bfb82fdbe7 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -21,7 +21,7 @@ from ..account.types import User
from ..utils import get_nodes
from .types import Error, MetaInput, MetaPath, Upload
from .utils import from_global_id_strict_type, snake_to_camel_case
-from .utils.error_codes import get_error_code_from_error
+from .utils.error_codes import CommonErrorCode, get_error_code_from_error
registry = get_global_registry()
@@ -62,7 +62,7 @@ def validation_error_to_error_type(validation_error: ValidationError) -> list:
# convert non-field errors
for err in validation_error.error_list:
err_list.append(
- Error(message=err.message, code=get_error_code_from_error(err))
+ Error(message=err.messages[0], code=get_error_code_from_error(err))
)
return err_list
@@ -143,11 +143,18 @@ class BaseMutation(graphene.Mutation):
node = cls.get_node_by_pk(info, graphene_type=only_type, pk=pk, qs=qs)
except (AssertionError, GraphQLError) as e:
- raise ValidationError({field: str(e)})
+ raise ValidationError(
+ {field: ValidationError(str(e), code=CommonErrorCode.GRAPHQL_ERROR)}
+ )
else:
if node is None:
raise ValidationError(
- {field: "Couldn't resolve to a node: %s" % node_id}
+ {
+ field: ValidationError(
+ "Couldn't resolve to a node: %s" % node_id,
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
return node
@@ -156,7 +163,9 @@ class BaseMutation(graphene.Mutation):
try:
instances = get_nodes(ids, only_type, qs=qs)
except GraphQLError as e:
- raise ValidationError({field: str(e)})
+ raise ValidationError(
+ {field: ValidationError(str(e), code=CommonErrorCode.GRAPHQL_ERROR)}
+ )
return instances
@classmethod
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index 82dc9d5057..1b4549244e 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -6,6 +6,8 @@ import graphene_django_optimizer as gql_optimizer
from django.core.exceptions import ValidationError
from graphene import ObjectType
+from .error_codes import CommonErrorCode
+
def clean_seo_fields(data):
"""Extract and assign seo fields to given dictionary."""
@@ -31,7 +33,13 @@ def str_to_enum(name):
def validate_image_file(file, field_name):
"""Validate if the file is an image."""
if not file.content_type.startswith("image/"):
- raise ValidationError({field_name: "Invalid file type"})
+ raise ValidationError(
+ {
+ field_name: ValidationError(
+ "Invalid file type", code=CommonErrorCode.INVALID_FILE_TYPE
+ )
+ }
+ )
def from_global_id_strict_type(
@@ -41,7 +49,14 @@ def from_global_id_strict_type(
try:
_type, _id = graphene.Node.from_global_id(global_id)
except (binascii.Error, UnicodeDecodeError) as exc:
- raise ValidationError({field: f"Couldn't resolve to a node"}) from exc
+ raise ValidationError(
+ {
+ field: ValidationError(
+ "Couldn't resolve to a node: %s" % global_id,
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
+ ) from exc
if str(_type) != str(only_type):
raise ValidationError({field: f"Must receive a {only_type} id"})
diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.py
index f812f76334..11614eadc8 100644
--- a/saleor/graphql/core/utils/error_codes.py
+++ b/saleor/graphql/core/utils/error_codes.py
@@ -1,3 +1,5 @@
+from enum import Enum
+
DJANGO_VALIDATORS_ERROR_CODES = [
"invalid",
"limit_value",
@@ -13,6 +15,7 @@ DJANGO_VALIDATORS_ERROR_CODES = [
]
DJANGO_FORM_FIELDS_ERROR_CODES = [
+ "required",
"overflow",
"missing",
"empty",
@@ -25,17 +28,145 @@ DJANGO_FORM_FIELDS_ERROR_CODES = [
"invalid_time",
]
+DJANGO_PASSWORD_VALIDATION_ERROR_CODES = [
+ "password_too_short",
+ "password_too_similar",
+ "password_too_common",
+ "password_entirely_numeric",
+]
+
+
+class AccountErrorCode(Enum):
+ INVALID_PHONE_NUMBER = "invalid_phone_number"
+ ACTIVATE_OWN_ACCOUNT = "activate_own_account"
+ ACTIVATE_SUPERUSER_ACCOUNT = "activate_superuser_account"
+ DEACTIVATE_OWN_ACCOUNT = "deactivate_own_account"
+ DEACTIVATE_SUPERUSER_ACCOUNT = "deactivate_superuser_account"
+ INVALID_COUNTRY = "invalid_country"
+ DELETE_STUFF_ACCOUNT = "delete_stuff_account"
+ INVALID_USER_TOKEN = "invalid_user_token"
+ NOT_USERS_ADDRESS = "not_users_address"
+ USER_DOES_NOT_EXIST = "user_does_not_exist"
+ DELETE_OWN_ACCOUNT = "delete_own_account"
+ DELETE_SUPERUSER_ACCOUNT = "delete_superuser_account"
+ DELETE_STAFF_ACCOUNT = "delete_staff_account"
+ DELETE_NON_STAFF_USER = "delete_non_staff_user"
+
+
+class CheckoutErrorCode(Enum):
+ VOUCHER_NOT_APPLICABLE = "voucher_not_applicable"
+ SHIPPING_METHOD_NOT_SET = "shipping_method_not_set"
+ SHIPPING_ADDRESS_NOT_SET = "shipping_address_not_set"
+ BILLING_ADDRESS_NOT_SET = "billing_address_not_set"
+ INVALID_SHIPPING_METHOD = "invalid_shipping_method"
+ CHECKOUT_NOT_FULLY_PAID = "checkout_not_fully_paid"
+ SHIPPING_NOT_REQUIRED = "shipping_not_required"
+ QUANTITY_GREATER_THAN_LIMIT = "quantity_greater_than_limit"
+ INSUFFICIENT_STOCK = "insufficient_stock"
+ SHIPPING_METHOD_NOT_APPLICABLE = "shipping_method_not_applicable"
+ TAX_ERROR = "tax_error"
+
+
+class MenuErrorCode(Enum):
+ TOO_MANY_MENU_ITEMS = "too_many_items"
+ NO_MENU_ITEM_PROVIDED = "no_item_provided"
+ INVALID_MENU_ITEM = "invalid_menu_item"
+ ASSIGN_MENU_ITEM_TO_ITSELF = "assign_menu_item_to_itself"
+ CANNOT_ASSIGN_NOTE = "cannot_assign_node"
+
+
+class OrderErrorCode(Enum):
+ DELETE_NON_DRAFT_ORDER = "delete_non_draft_order"
+ DELETE_LINE_NON_DRAFT_ORDER = "delete_line_non_draft_order"
+ EDIT_NON_DRAFT_ORDER = "edit_non_draft_order"
+ QUANTITY_LESS_THAN_ONE = "quantity_less_than_one"
+ FULFILL_ORDER_LINE = "fulfill_order_line"
+ CANNOT_CANCEL_FULFILLMENT = "cannot_cancel_fulfillment"
+ CANNOT_CANCEL_ORDER = "cannot_cancel_order"
+ ORDER_NO_PAYMENT = "order_no_payment"
+ CAPTURE_INACTIVE_PAYMENT = "capture_inactive_payment"
+ VOID_INACTIVE_PAYMENT = "void_inactive_payment"
+ REFUND_MANUAL_PAYMENT = "refund_manual_payment"
+ ORDER_NO_PRODUCTS = "order_without_products"
+ VARIANT_DOES_NOT_EXIST = "variant_does_not_exist"
+ ORDER_NO_SHIPPING_ADDRESS = "order_no_shipping_address"
+ ORDER_INVALID_SHIPPING_METHOD = "order_invalid_shipping_method"
+
+
+class CommonErrorCode(Enum):
+ PAYMENT_ERROR = "payment_error"
+ PARTIAL_PAYMENT_NOT_ALLOWED = "partial_payment_not_allowed"
+ SHIPPING_METHOD_REQUIRED = "shipping_method_required"
+ POSITIVE_NUMBER_REQUIRED = "positive_number_required"
+ DOES_NOT_EXIST = "does_not_exist"
+ VALUE_ERROR = "value_error"
+ NON_BLANK_VALUE_REQUIRED = "non_blank_value_required"
+ MISSING_VALUE = "missing_value"
+ INCORRECT_VALUE = "incorrect_value"
+ CANNOT_FETCH_TAX_RATES = "cannot_fetch_tax_rates"
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID_FILE_TYPE = "invalid_file_type"
+ INVALID_STOREFRONT_URL = "invalid_storefront_url"
+ AUTHORIZATION_KEY_ALREADY_EXISTS = "authorization_key_already_exists"
+
+
+class AttributeErrorCode(Enum):
+ ATTRIBUTE_ALREADY_EXISTS = "attribute_already_exists"
+ ATTRIBUTE_VALUES_NOT_UNIQUE = "attribute_values_not_unique"
+ ATTRIBUTE_SLUG_BLANK = "attribute_slug_blank"
+ ATTRIBUTE_SLUG_ALREADY_EXISTS = "attribute_slug_already_exists"
+ ATTRIBUTE_BAD_VALUE = "attribute_bad_value"
+ ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"
+ ATTRIBUTE_NON_ASSIGNABLE = "attribute_non_assignable"
+ ATTRIBUTE_CANNOT_BE_ASSIGNED = "attribute_cannot_be_assigned"
+ ATTRIBUTE_DISABLED_VARIANTS = "attribute_disabled_variants"
+
+
+class DigitalContentErrorCode(Enum):
+ MISSING_CONFIGURATION_FIELDS = "missing_configuration_fields"
+ VARIANT_NO_DIGITAL_CONTENT = "variant_no_digital_content"
+
+
+class ProductErrorCode(Enum):
+ PRODUCT_ALREADY_EXISTS = "product_already_exists"
+ NOT_PRODUCTS_IMAGE = "not_products_image"
+
+
+class ShippingErrorCode(Enum):
+ DEFAULT_SHIPPING_ZONE_ALREADY_EXISTS = "default_shipping_zone_already_exists"
+ MAX_LESS_THAN_MIN = "max_less_than_min"
+
+
ERROR_CODE_UNKNOWN = "unknown"
+SALEOR_ERROR_CODE_ENUMS = [
+ AccountErrorCode,
+ CheckoutErrorCode,
+ MenuErrorCode,
+ OrderErrorCode,
+ CommonErrorCode,
+ AttributeErrorCode,
+ DigitalContentErrorCode,
+ ProductErrorCode,
+ ShippingErrorCode,
+]
+
+saleor_error_codes = []
+for enum in SALEOR_ERROR_CODE_ENUMS:
+ saleor_error_codes.extend([code.value for code in enum])
+
+
ERROR_CODES = (
[ERROR_CODE_UNKNOWN]
+ DJANGO_VALIDATORS_ERROR_CODES
+ DJANGO_FORM_FIELDS_ERROR_CODES
+ + DJANGO_PASSWORD_VALIDATION_ERROR_CODES
+ + saleor_error_codes
)
def get_error_code_from_error(error):
- """ """
+ """Return valid error code or UNKNOWN for unknown error code."""
code = error.code
if code not in ERROR_CODES:
return ERROR_CODE_UNKNOWN
diff --git a/saleor/graphql/giftcard/mutations.py b/saleor/graphql/giftcard/mutations.py
index 348e9d15e8..556aa44496 100644
--- a/saleor/graphql/giftcard/mutations.py
+++ b/saleor/graphql/giftcard/mutations.py
@@ -11,6 +11,7 @@ from ...giftcard import models
from ...giftcard.utils import activate_gift_card, deactivate_gift_card
from ..core.mutations import BaseMutation, ModelMutation
from ..core.scalars import Decimal
+from ..core.utils.error_codes import AccountErrorCode
from .types import GiftCard
@@ -60,7 +61,12 @@ class GiftCardCreate(ModelMutation):
cleaned_input["user"] = User.objects.get(email=user_email)
except ObjectDoesNotExist:
raise ValidationError(
- {"email": "Customer with this email doesn't exist."}
+ {
+ "email": ValidationError(
+ "Customer with this email doesn't exist.",
+ code=AccountErrorCode.USER_DOES_NOT_EXIST,
+ )
+ }
)
return cleaned_input
diff --git a/saleor/graphql/menu/mutations.py b/saleor/graphql/menu/mutations.py
index a44cf129e7..8f5f682c26 100644
--- a/saleor/graphql/menu/mutations.py
+++ b/saleor/graphql/menu/mutations.py
@@ -11,6 +11,7 @@ from ...menu.utils import update_menu
from ...page import models as page_models
from ...product import models as product_models
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ..core.utils.error_codes import MenuErrorCode
from ..page.types import Page
from ..product.types import Category, Collection
from .enums import NavigationType
@@ -72,7 +73,14 @@ class MenuCreate(ModelMutation):
page = item.get("page")
url = item.get("url")
if len([i for i in [category, collection, page, url] if i]) > 1:
- raise ValidationError({"items": "More than one item provided."})
+ raise ValidationError(
+ {
+ "items": ValidationError(
+ "More than one item provided.",
+ code=MenuErrorCode.TOO_MANY_MENU_ITEMS,
+ )
+ }
+ )
if category:
category = cls.get_node_or_error(
@@ -88,7 +96,14 @@ class MenuCreate(ModelMutation):
page = cls.get_node_or_error(info, page, field="items", only_type=Page)
item["page"] = page
elif not url:
- raise ValidationError({"items": "No menu item provided."})
+ raise ValidationError(
+ {
+ "items": ValidationError(
+ "No menu item provided.",
+ code=MenuErrorCode.NO_MENU_ITEM_PROVIDED,
+ )
+ }
+ )
items.append(item)
cleaned_input["items"] = items
@@ -136,7 +151,9 @@ def _validate_menu_item_instance(
f"Enter a valid {expected_model._meta.verbose_name} ID "
f"(got {item._meta.verbose_name} ID)."
)
- raise ValidationError({field: msg})
+ raise ValidationError(
+ {field: ValidationError(msg, code=MenuErrorCode.INVALID_MENU_ITEM)}
+ )
class MenuItemCreate(ModelMutation):
@@ -171,7 +188,9 @@ class MenuItemCreate(ModelMutation):
]
items = [item for item in items if item is not None]
if len(items) > 1:
- raise ValidationError("More than one item provided.")
+ raise ValidationError(
+ "More than one item provided.", code=MenuErrorCode.TOO_MANY_MENU_ITEMS
+ )
return cleaned_input
@classmethod
@@ -244,7 +263,14 @@ class MenuItemMove(BaseMutation):
"""Validate if the given move could be possibly possible."""
if move.parent_id:
if move.item_id == move.parent_id:
- raise ValidationError({"parent": "Cannot assign a node to itself."})
+ raise ValidationError(
+ {
+ "parent": ValidationError(
+ "Cannot assign a node to itself.",
+ code=MenuErrorCode.ASSIGN_MENU_ITEM_TO_ITSELF,
+ )
+ }
+ )
@staticmethod
def clean_operation(operation: _MenuMoveOperation):
@@ -254,9 +280,12 @@ class MenuItemMove(BaseMutation):
if operation.menu_item.is_ancestor_of(operation.parent):
raise ValidationError(
{
- "parent": (
- "Cannot assign a node as child of "
- "one of its descendants."
+ "parent": ValidationError(
+ (
+ "Cannot assign a node as child of "
+ "one of its descendants."
+ ),
+ code=MenuErrorCode.CANNOT_ASSIGN_NOTE,
)
}
)
diff --git a/saleor/graphql/order/bulk_mutations/draft_orders.py b/saleor/graphql/order/bulk_mutations/draft_orders.py
index a8f9320eca..a96be4aa85 100644
--- a/saleor/graphql/order/bulk_mutations/draft_orders.py
+++ b/saleor/graphql/order/bulk_mutations/draft_orders.py
@@ -3,6 +3,7 @@ from django.core.exceptions import ValidationError
from ....order import OrderStatus, models
from ...core.mutations import ModelBulkDeleteMutation
+from ...core.utils.error_codes import OrderErrorCode
class DraftOrderBulkDelete(ModelBulkDeleteMutation):
@@ -19,7 +20,14 @@ class DraftOrderBulkDelete(ModelBulkDeleteMutation):
@classmethod
def clean_instance(cls, info, instance):
if instance.status != OrderStatus.DRAFT:
- raise ValidationError({"id": "Cannot delete non-draft orders."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot delete non-draft orders.",
+ code=OrderErrorCode.DELETE_NON_DRAFT_ORDER,
+ )
+ }
+ )
class DraftOrderLinesBulkDelete(ModelBulkDeleteMutation):
@@ -36,4 +44,11 @@ class DraftOrderLinesBulkDelete(ModelBulkDeleteMutation):
@classmethod
def clean_instance(cls, _info, instance):
if instance.order.status != OrderStatus.DRAFT:
- raise ValidationError({"id": "Cannot delete line for non-draft orders."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Cannot delete line for non-draft orders.",
+ code=OrderErrorCode.DELETE_LINE_NON_DRAFT_ORDER,
+ )
+ }
+ )
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index 08e5008b1a..995522fc13 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -18,6 +18,7 @@ from ...account.i18n import I18nMixin
from ...account.types import AddressInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import Decimal
+from ...core.utils.error_codes import OrderErrorCode
from ...product.types import ProductVariant
from ..types import Order, OrderLine
from ..utils import validate_draft_order
@@ -288,7 +289,14 @@ class DraftOrderLinesCreate(BaseMutation):
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
if order.status != OrderStatus.DRAFT:
- raise ValidationError({"id": "Only draft orders can be edited."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Only draft orders can be edited.",
+ code=OrderErrorCode.EDIT_NON_DRAFT_ORDER,
+ )
+ }
+ )
lines_to_add = []
for input_line in data.get("input"):
@@ -302,7 +310,12 @@ class DraftOrderLinesCreate(BaseMutation):
lines_to_add.append((quantity, variant))
else:
raise ValidationError(
- {"quantity": "Ensure this value is greater than or equal to 1."}
+ {
+ "quantity": ValidationError(
+ "Ensure this value is greater than or equal to 1.",
+ code=OrderErrorCode.QUANTITY_LESS_THAN_ONE,
+ )
+ }
)
# Add the lines
@@ -338,7 +351,14 @@ class DraftOrderLineDelete(BaseMutation):
line = cls.get_node_or_error(info, id, only_type=OrderLine)
order = line.order
if order.status != OrderStatus.DRAFT:
- raise ValidationError({"id": "Only draft orders can be edited."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Only draft orders can be edited.",
+ code=OrderErrorCode.EDIT_NON_DRAFT_ORDER,
+ )
+ }
+ )
db_id = line.id
delete_order_line(line)
@@ -372,12 +392,24 @@ class DraftOrderLineUpdate(ModelMutation):
instance.old_quantity = instance.quantity
cleaned_input = super().clean_input(info, instance, data)
if instance.order.status != OrderStatus.DRAFT:
- raise ValidationError({"id": "Only draft orders can be edited."})
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Only draft orders can be edited.",
+ code=OrderErrorCode.EDIT_NON_DRAFT_ORDER,
+ )
+ }
+ )
quantity = data["quantity"]
if quantity <= 0:
raise ValidationError(
- {"quantity": "Ensure this value is greater than or equal to 1."}
+ {
+ "quantity": ValidationError(
+ "Ensure this value is greater than or equal to 1.",
+ code=OrderErrorCode.QUANTITY_LESS_THAN_ONE,
+ )
+ }
)
return cleaned_input
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 6b42f37997..103e26ce08 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -6,6 +6,7 @@ from ....order import events, models
from ....order.emails import send_fulfillment_confirmation_to_customer
from ....order.utils import cancel_fulfillment, fulfill_order_line, update_order_status
from ...core.mutations import BaseMutation
+from ...core.utils.error_codes import CommonErrorCode, OrderErrorCode
from ...order.types import Fulfillment, Order
from ..types import OrderLine
@@ -67,7 +68,13 @@ class FulfillmentCreate(BaseMutation):
"quantity": order_line.quantity_unfulfilled,
"order_line": order_line,
}
- raise ValidationError({"order_line_id": msg})
+ raise ValidationError(
+ {
+ "order_line_id": ValidationError(
+ msg, code=OrderErrorCode.FULFILL_ORDER_LINE
+ )
+ }
+ )
@classmethod
def clean_input(cls, data):
@@ -81,7 +88,14 @@ class FulfillmentCreate(BaseMutation):
cls.clean_lines(order_lines, quantities)
if sum(quantities) <= 0:
- raise ValidationError({"lines": "Total quantity must be larger than 0."})
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Total quantity must be larger than 0.",
+ code=CommonErrorCode.POSITIVE_NUMBER_REQUIRED,
+ )
+ }
+ )
data["order_lines"] = order_lines
data["quantities"] = quantities
@@ -183,7 +197,13 @@ class FulfillmentCancel(BaseMutation):
"Cancel fulfillment mutation error",
"This fulfillment can't be canceled",
)
- raise ValidationError({"fulfillment": err_msg})
+ raise ValidationError(
+ {
+ "fulfillment": ValidationError(
+ err_msg, code=OrderErrorCode.CANNOT_CANCEL_FULFILLMENT
+ )
+ }
+ )
order = fulfillment.order
cancel_fulfillment(info.context.user, fulfillment, restock)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 98442d5aa6..c306bb5396 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -20,6 +20,7 @@ from ....payment.utils import (
from ...account.types import AddressInput
from ...core.mutations import BaseMutation
from ...core.scalars import Decimal
+from ...core.utils.error_codes import CommonErrorCode, OrderErrorCode
from ...order.mutations.draft_orders import DraftOrderUpdate
from ...order.types import Order, OrderEvent
from ...shipping.types import ShippingMethod
@@ -29,8 +30,11 @@ def clean_order_update_shipping(order, method):
if not order.shipping_address:
raise ValidationError(
{
- "order": "Cannot choose a shipping method for an order without "
- "the shipping address."
+ "order": ValidationError(
+ "Cannot choose a shipping method for an order without "
+ "the shipping address.",
+ code=OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS,
+ )
}
)
@@ -39,19 +43,36 @@ def clean_order_update_shipping(order, method):
"id", flat=True
):
raise ValidationError(
- {"shipping_method": "Shipping method cannot be used with this order."}
+ {
+ "shipping_method": ValidationError(
+ "Shipping method cannot be used with this order.",
+ code=OrderErrorCode.ORDER_INVALID_SHIPPING_METHOD,
+ )
+ }
)
def clean_order_cancel(order):
if order and not order.can_cancel():
- raise ValidationError({"order": "This order can't be canceled."})
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "This order can't be canceled.",
+ code=OrderErrorCode.CANNOT_CANCEL_ORDER,
+ )
+ }
+ )
def clean_payment(payment):
if not payment:
raise ValidationError(
- {"payment": "There's no payment associated with the order."}
+ {
+ "payment": ValidationError(
+ "There's no payment associated with the order.",
+ code=OrderErrorCode.ORDER_NO_PAYMENT,
+ )
+ }
)
@@ -59,7 +80,12 @@ def clean_order_capture(payment):
clean_payment(payment)
if not payment.is_active:
raise ValidationError(
- {"payment": "Only pre-authorized payments can be captured"}
+ {
+ "payment": ValidationError(
+ "Only pre-authorized payments can be captured",
+ code=OrderErrorCode.CAPTURE_INACTIVE_PAYMENT,
+ )
+ }
)
@@ -67,13 +93,27 @@ def clean_void_payment(payment):
"""Check for payment errors."""
clean_payment(payment)
if not payment.is_active:
- raise ValidationError({"payment": "Only pre-authorized payments can be voided"})
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "Only pre-authorized payments can be voided",
+ code=OrderErrorCode.VOID_INACTIVE_PAYMENT,
+ )
+ }
+ )
def clean_refund_payment(payment):
clean_payment(payment)
if payment.gateway == CustomPaymentChoices.MANUAL:
- raise ValidationError({"payment": "Manual payments can not be refunded."})
+ raise ValidationError(
+ {
+ "payment": ValidationError(
+ "Manual payments can not be refunded.",
+ code=OrderErrorCode.REFUND_MANUAL_PAYMENT,
+ )
+ }
+ )
def try_payment_action(order, user, payment, func, *args, **kwargs):
@@ -84,7 +124,9 @@ def try_payment_action(order, user, payment, func, *args, **kwargs):
events.payment_failed_event(
order=order, user=user, message=message, payment=payment
)
- raise ValidationError({"payment": message})
+ raise ValidationError(
+ {"payment": ValidationError(message, code=CommonErrorCode.PAYMENT_ERROR)}
+ )
return True
@@ -146,7 +188,12 @@ class OrderUpdateShipping(BaseMutation):
if not data["shipping_method"]:
if not order.is_draft() and order.is_shipping_required():
raise ValidationError(
- {"shipping_method": "Shipping method is required for this order."}
+ {
+ "shipping_method": ValidationError(
+ "Shipping method is required for this order.",
+ code=CommonErrorCode.SHIPPING_METHOD_REQUIRED,
+ )
+ }
)
order.shipping_method = None
@@ -278,7 +325,14 @@ class OrderCapture(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, amount, **data):
if amount <= 0:
- raise ValidationError({"amount": "Amount should be a positive number."})
+ raise ValidationError(
+ {
+ "amount": ValidationError(
+ "Amount should be a positive number.",
+ code=CommonErrorCode.POSITIVE_NUMBER_REQUIRED,
+ )
+ }
+ )
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
payment = order.get_last_payment()
@@ -332,7 +386,14 @@ class OrderRefund(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, amount, **data):
if amount <= 0:
- raise ValidationError({"amount": "Amount should be a positive number."})
+ raise ValidationError(
+ {
+ "amount": ValidationError(
+ "Amount should be a positive number.",
+ code=CommonErrorCode.POSITIVE_NUMBER_REQUIRED,
+ )
+ }
+ )
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
payment = order.get_last_payment()
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 11738a427e..2febf77b9b 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -1,9 +1,18 @@
from django.core.exceptions import ValidationError
+from ..core.utils.error_codes import OrderErrorCode
+
def validate_total_quantity(order):
if order.get_total_quantity() == 0:
- raise ValidationError({"lines": "Could not create order without any products."})
+ raise ValidationError(
+ {
+ "lines": ValidationError(
+ "Could not create order without any products.",
+ code=OrderErrorCode.ORDER_NO_PRODUCTS,
+ )
+ }
+ )
def validate_shipping_method(order):
@@ -16,7 +25,12 @@ def validate_shipping_method(order):
) # noqa
if shipping_not_valid:
raise ValidationError(
- {"shipping": "Shipping method is not valid for chosen shipping address"}
+ {
+ "shipping": ValidationError(
+ "Shipping method is not valid for chosen shipping address",
+ code=OrderErrorCode.ORDER_INVALID_SHIPPING_METHOD,
+ )
+ }
)
@@ -24,7 +38,12 @@ def validate_order_lines(order):
for line in order:
if line.variant is None:
raise ValidationError(
- {"lines": "Could not create orders with non-existing products."}
+ {
+ "lines": ValidationError(
+ "Could not create orders with non-existing products.",
+ code=OrderErrorCode.VARIANT_DOES_NOT_EXIST,
+ )
+ }
)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index b78b510d31..22cd819ae2 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -18,6 +18,7 @@ from ..checkout.types import Checkout
from ..core.mutations import BaseMutation
from ..core.scalars import Decimal
from ..core.utils import from_global_id_strict_type
+from ..core.utils.error_codes import CheckoutErrorCode, CommonErrorCode
from .enums import PaymentGatewayEnum
from .types import Payment
@@ -77,7 +78,12 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
billing_address = cls.validate_address(data["billing_address"])
if billing_address is None:
raise ValidationError(
- {"billing_address": "No billing address associated with this checkout."}
+ {
+ "billing_address": ValidationError(
+ "No billing address associated with this checkout.",
+ code=CheckoutErrorCode.BILLING_ADDRESS_NOT_SET,
+ )
+ }
)
checkout_total = (
@@ -91,8 +97,11 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
if amount < checkout_total.gross.amount:
raise ValidationError(
{
- "amount": "Partial payments are not allowed, amount should be "
- "equal checkout's total."
+ "amount": ValidationError(
+ "Partial payments are not allowed, amount should be "
+ "equal checkout's total.",
+ code=CommonErrorCode.PARTIAL_PAYMENT_NOT_ALLOWED,
+ )
}
)
@@ -131,7 +140,7 @@ class PaymentCapture(BaseMutation):
try:
gateway_capture(payment, amount)
except PaymentError as e:
- raise ValidationError(str(e))
+ raise ValidationError(str(e), code=CommonErrorCode.PAYMENT_ERROR)
return PaymentCapture(payment=payment)
@@ -148,7 +157,7 @@ class PaymentRefund(PaymentCapture):
try:
gateway_refund(payment, amount=amount)
except PaymentError as e:
- raise ValidationError(str(e))
+ raise ValidationError(str(e), code=CommonErrorCode.PAYMENT_ERROR)
return PaymentRefund(payment=payment)
@@ -170,7 +179,7 @@ class PaymentVoid(BaseMutation):
try:
gateway_void(payment)
except PaymentError as e:
- raise ValidationError(str(e))
+ raise ValidationError(str(e), CommonErrorCode.PAYMENT_ERROR)
return PaymentVoid(payment=payment)
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 82ea0f1bde..4e7c7602e8 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -15,6 +15,7 @@ from ...core.mutations import (
UpdateMetaBaseMutation,
)
from ...core.utils import from_global_id_strict_type
+from ...core.utils.error_codes import AttributeErrorCode, CommonErrorCode
from ...core.utils.reordering import perform_reordering
from ...product.types import ProductType
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
@@ -116,12 +117,23 @@ class AttributeMixin:
"Value %s already exists within this attribute."
% value_data["name"]
)
- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})
+ raise ValidationError(
+ {
+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
+ msg, code=AttributeErrorCode.ATTRIBUTE_ALREADY_EXISTS
+ )
+ }
+ )
new_slugs = [slugify(value_data["name"]) for value_data in values_input]
if len(set(new_slugs)) != len(new_slugs):
raise ValidationError(
- {cls.ATTRIBUTE_VALUES_FIELD: "Provided values are not unique."}
+ {
+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
+ "Provided values are not unique.",
+ code=AttributeErrorCode.ATTRIBUTE_VALUES_NOT_UNIQUE,
+ )
+ }
)
@classmethod
@@ -143,11 +155,10 @@ class AttributeMixin:
try:
attribute_value.full_clean()
except ValidationError as validation_errors:
- for field in validation_errors.message_dict:
+ for field, err in validation_errors.error_dict.items():
if field == "attribute":
continue
- for msg in validation_errors.message_dict[field]:
- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})
+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: err})
cls.check_values_are_unique(values_input, attribute)
@classmethod
@@ -156,7 +167,14 @@ class AttributeMixin:
if input_slug is None:
cleaned_input["slug"] = slugify(cleaned_input["name"])
elif input_slug == "":
- raise ValidationError({"slug": "The attribute's slug cannot be blank."})
+ raise ValidationError(
+ {
+ "slug": ValidationError(
+ "The attribute's slug cannot be blank.",
+ code=AttributeErrorCode.ATTRIBUTE_SLUG_BLANK,
+ )
+ }
+ )
query = models.Attribute.objects.filter(slug=cleaned_input["slug"])
@@ -164,7 +182,14 @@ class AttributeMixin:
query = query.exclude(pk=instance.pk)
if query.exists():
- raise ValidationError({"slug": "This attribute's slug already exists."})
+ raise ValidationError(
+ {
+ "slug": ValidationError(
+ "This attribute's slug already exists.",
+ code=AttributeErrorCode.ATTRIBUTE_SLUG_ALREADY_EXISTS,
+ )
+ }
+ )
return cleaned_input
@@ -239,7 +264,13 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
for value in remove_values:
if value.attribute != instance:
msg = "Value %s does not belong to this attribute." % value
- raise ValidationError({"remove_values": msg})
+ raise ValidationError(
+ {
+ "remove_values": ValidationError(
+ msg, code=AttributeErrorCode.ATTRIBUTE_BAD_VALUE
+ )
+ }
+ )
return remove_values
@classmethod
@@ -323,8 +354,9 @@ class AttributeAssign(BaseMutation):
msg = ", ".join([f"{name} ({slug})" for name, slug in invalid_attributes])
raise ValidationError(
{
- "operations": (
- f"{msg} have already been assigned to this product type."
+ "operations": ValidationError(
+ (f"{msg} have already been assigned to this product type."),
+ code=AttributeErrorCode.ATTRIBUTE_ALREADY_ASSIGNED,
)
}
)
@@ -338,10 +370,13 @@ class AttributeAssign(BaseMutation):
if is_not_assignable_to_variant:
raise ValidationError(
{
- "operations": (
- f"Attributes having for input types "
- f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "
- f"cannot be assigned as variant attributes"
+ "operations": ValidationError(
+ (
+ f"Attributes having for input types "
+ f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "
+ f"cannot be assigned as variant attributes"
+ ),
+ code=AttributeErrorCode.ATTRIBUTE_NON_ASSIGNABLE,
)
}
)
@@ -354,7 +389,12 @@ class AttributeAssign(BaseMutation):
if contains_restricted_attributes:
raise ValidationError(
- {"operations": ("Cannot assign variant only attributes.")}
+ {
+ "operations": ValidationError(
+ "Cannot assign variant only attributes.",
+ code=AttributeErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
+ )
+ }
)
@classmethod
@@ -387,7 +427,12 @@ class AttributeAssign(BaseMutation):
if variant_attrs_pks and not product_type.has_variants:
raise ValidationError(
- {"operations": "Variants are disabled in this product type."}
+ {
+ "operations": ValidationError(
+ "Variants are disabled in this product type.",
+ code=AttributeErrorCode.ATTRIBUTE_DISABLED_VARIANTS,
+ )
+ }
)
# Ensure the attribute are assignable
@@ -496,7 +541,14 @@ def validate_value_is_unique(attribute: models.Attribute, value: models.Attribut
"""Check if the attribute value is unique within the attribute it belongs to."""
duplicated_values = attribute.values.exclude(pk=value.pk).filter(slug=value.slug)
if duplicated_values.exists():
- raise ValidationError({"name": f"Value with slug {value.slug} already exists."})
+ raise ValidationError(
+ {
+ "name": ValidationError(
+ f"Value with slug {value.slug} already exists.",
+ code=AttributeErrorCode.ATTRIBUTE_SLUG_ALREADY_EXISTS,
+ )
+ }
+ )
class AttributeValueCreate(ModelMutation):
@@ -635,8 +687,9 @@ class ProductTypeReorderAttributes(BaseMutation):
except ObjectDoesNotExist:
raise ValidationError(
{
- "product_type_id": (
- f"Couldn't resolve to a product type: {product_type_id}"
+ "product_type_id": ValidationError(
+ (f"Couldn't resolve to a product type: {product_type_id}"),
+ code=CommonErrorCode.DOES_NOT_EXIST,
)
}
)
@@ -654,7 +707,12 @@ class ProductTypeReorderAttributes(BaseMutation):
m2m_info = attributes_m2m.get(attribute_id=int(attribute_pk))
except ObjectDoesNotExist:
raise ValidationError(
- {"moves": f"Couldn't resolve to an attribute: {move_info.id}"}
+ {
+ "moves": ValidationError(
+ f"Couldn't resolve to an attribute: {move_info.id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
operations[m2m_info.pk] = move_info.sort_order
@@ -692,7 +750,12 @@ class AttributeReorderValues(BaseMutation):
attribute = models.Attribute.objects.prefetch_related("values").get(pk=pk)
except ObjectDoesNotExist:
raise ValidationError(
- {"attribute_id": (f"Couldn't resolve to an attribute: {attribute_id}")}
+ {
+ "attribute_id": ValidationError(
+ f"Couldn't resolve to an attribute: {attribute_id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
values_m2m = attribute.values
@@ -708,7 +771,12 @@ class AttributeReorderValues(BaseMutation):
m2m_info = values_m2m.get(pk=int(value_pk))
except ObjectDoesNotExist:
raise ValidationError(
- {"moves": f"Couldn't resolve to an attribute value: {move_info.id}"}
+ {
+ "moves": ValidationError(
+ f"Couldn't resolve to an attribute value: {move_info.id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
operations[m2m_info.pk] = move_info.sort_order
diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.py
index 7b843563fc..37fff164a5 100644
--- a/saleor/graphql/product/mutations/digital_contents.py
+++ b/saleor/graphql/product/mutations/digital_contents.py
@@ -4,6 +4,7 @@ from django.core.exceptions import ValidationError
from ....product import models
from ...core.mutations import BaseMutation, ModelMutation
from ...core.types import Upload
+from ...core.utils.error_codes import DigitalContentErrorCode
from ...decorators import permission_required
from ..types import DigitalContent, ProductVariant
@@ -77,7 +78,10 @@ class DigitalContentCreate(BaseMutation):
missing_fields = set(required_fields).difference(set(data))
if missing_fields:
msg += "{}, " * len(missing_fields)
- raise ValidationError(msg.format(*missing_fields))
+ raise ValidationError(
+ msg.format(*missing_fields),
+ code=DigitalContentErrorCode.MISSING_CONFIGURATION_FIELDS,
+ )
return data
@@ -165,7 +169,10 @@ class DigitalContentUpdate(BaseMutation):
missing_fields = set(required_fields).difference(set(data))
if missing_fields:
msg += "{}, " * len(missing_fields)
- raise ValidationError(msg.format(*missing_fields))
+ raise ValidationError(
+ msg.format(*missing_fields),
+ code=DigitalContentErrorCode.MISSING_CONFIGURATION_FIELDS,
+ )
return data
@@ -178,7 +185,13 @@ class DigitalContentUpdate(BaseMutation):
if not hasattr(variant, "digital_content"):
msg = "Variant %s doesn't have any digital content" % variant.id
- raise ValidationError({"variantId": msg})
+ raise ValidationError(
+ {
+ "variantId": ValidationError(
+ msg, code=DigitalContentErrorCode.VARIANT_NO_DIGITAL_CONTENT
+ )
+ }
+ )
clean_input = cls.clean_input(info, data.get("input"))
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 40bc7b38aa..1b8b5cd604 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -37,6 +37,7 @@ from ...core.utils import (
from_global_id_strict_type,
validate_image_file,
)
+from ...core.utils.error_codes import CommonErrorCode, ProductErrorCode
from ...core.utils.reordering import perform_reordering
from ..types import (
Category,
@@ -247,7 +248,12 @@ class CollectionReorderProducts(BaseMutation):
).get(pk=pk)
except ObjectDoesNotExist:
raise ValidationError(
- {"collection_id": f"Couldn't resolve to a collection: {collection_id}"}
+ {
+ "collection_id": ValidationError(
+ f"Couldn't resolve to a collection: {collection_id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
m2m_related_field = collection.collectionproduct
@@ -264,7 +270,12 @@ class CollectionReorderProducts(BaseMutation):
m2m_info = m2m_related_field.get(product_id=int(product_pk))
except ObjectDoesNotExist:
raise ValidationError(
- {"moves": f"Couldn't resolve to a product: {move_info.product_id}"}
+ {
+ "moves": ValidationError(
+ f"Couldn't resolve to a product: {move_info.product_id}",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
)
operations[m2m_info.pk] = move_info.sort_order
@@ -732,9 +743,23 @@ class ProductCreate(ModelMutation):
if product_type and not product_type.has_variants:
input_sku = cleaned_input.get("sku")
if not input_sku:
- raise ValidationError({"sku": "This field cannot be blank."})
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "This field cannot be blank.",
+ code=CommonErrorCode.NON_BLANK_VALUE_REQUIRED,
+ )
+ }
+ )
elif models.ProductVariant.objects.filter(sku=input_sku).exists():
- raise ValidationError({"sku": "Product with this SKU already exists."})
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Product with this SKU already exists.",
+ code=ProductErrorCode.PRODUCT_ALREADY_EXISTS,
+ )
+ }
+ )
@classmethod
def get_instance(cls, info, **data):
@@ -803,7 +828,14 @@ class ProductUpdate(ProductCreate):
and input_sku
and models.ProductVariant.objects.filter(sku=input_sku).exists()
):
- raise ValidationError({"sku": "Product with this SKU already exists."})
+ raise ValidationError(
+ {
+ "sku": ValidationError(
+ "Product with this SKU already exists.",
+ code=ProductErrorCode.PRODUCT_ALREADY_EXISTS,
+ )
+ }
+ )
@classmethod
@transaction.atomic
@@ -1292,7 +1324,14 @@ class ProductImageReorder(BaseMutation):
info, product_id, field="product_id", only_type=Product
)
if len(images_ids) != product.images.count():
- raise ValidationError({"order": "Incorrect number of image IDs provided."})
+ raise ValidationError(
+ {
+ "order": ValidationError(
+ "Incorrect number of image IDs provided.",
+ code=CommonErrorCode.INCORRECT_VALUE,
+ )
+ }
+ )
images = []
for image_id in images_ids:
@@ -1301,8 +1340,13 @@ class ProductImageReorder(BaseMutation):
)
if image and image.product != product:
raise ValidationError(
- {"order": "Image %(image_id)s does not belong to this product."},
- params={"image_id": image_id},
+ {
+ "order": ValidationError(
+ "Image %(image_id)s does not belong to this product.",
+ code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
+ params={"image_id": image_id},
+ )
+ }
)
images.append(image)
@@ -1364,7 +1408,12 @@ class VariantImageAssign(BaseMutation):
image.variant_images.create(variant=variant)
else:
raise ValidationError(
- {"image_id": "This image doesn't belong to that product."}
+ {
+ "image_id": ValidationError(
+ "This image doesn't belong to that product.",
+ code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
+ )
+ }
)
return VariantImageAssign(product_variant=variant, image=image)
@@ -1399,7 +1448,12 @@ class VariantImageUnassign(BaseMutation):
)
except models.VariantImage.DoesNotExist:
raise ValidationError(
- {"image_id": "Image is not assigned to this variant."}
+ {
+ "image_id": ValidationError(
+ "Image is not assigned to this variant.",
+ code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
+ )
+ }
)
else:
variant_image.delete()
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 174861a6ed..3c42799730 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1398,6 +1398,7 @@ enum ErrorCode {
MAX_WHOLE_DIGITS
INVALID_EXTENSION
NULL_CHARACTERS_NOT_ALLOWED
+ REQUIRED
OVERFLOW
MISSING
EMPTY
@@ -1408,6 +1409,84 @@ enum ErrorCode {
INCOMPLETE
INVALID_DATE
INVALID_TIME
+ PASSWORD_TOO_SHORT
+ PASSWORD_TOO_SIMILAR
+ PASSWORD_TOO_COMMON
+ PASSWORD_ENTIRELY_NUMERIC
+ INVALID_PHONE_NUMBER
+ ACTIVATE_OWN_ACCOUNT
+ ACTIVATE_SUPERUSER_ACCOUNT
+ DEACTIVATE_OWN_ACCOUNT
+ DEACTIVATE_SUPERUSER_ACCOUNT
+ INVALID_COUNTRY
+ DELETE_STUFF_ACCOUNT
+ INVALID_USER_TOKEN
+ NOT_USERS_ADDRESS
+ USER_DOES_NOT_EXIST
+ DELETE_OWN_ACCOUNT
+ DELETE_SUPERUSER_ACCOUNT
+ DELETE_STAFF_ACCOUNT
+ DELETE_NON_STAFF_USER
+ VOUCHER_NOT_APPLICABLE
+ SHIPPING_METHOD_NOT_SET
+ SHIPPING_ADDRESS_NOT_SET
+ BILLING_ADDRESS_NOT_SET
+ INVALID_SHIPPING_METHOD
+ CHECKOUT_NOT_FULLY_PAID
+ SHIPPING_NOT_REQUIRED
+ QUANTITY_GREATER_THAN_LIMIT
+ INSUFFICIENT_STOCK
+ SHIPPING_METHOD_NOT_APPLICABLE
+ TAX_ERROR
+ TOO_MANY_ITEMS
+ NO_ITEM_PROVIDED
+ INVALID_MENU_ITEM
+ ASSIGN_MENU_ITEM_TO_ITSELF
+ CANNOT_ASSIGN_NODE
+ DELETE_NON_DRAFT_ORDER
+ DELETE_LINE_NON_DRAFT_ORDER
+ EDIT_NON_DRAFT_ORDER
+ QUANTITY_LESS_THAN_ONE
+ FULFILL_ORDER_LINE
+ CANNOT_CANCEL_FULFILLMENT
+ CANNOT_CANCEL_ORDER
+ ORDER_NO_PAYMENT
+ CAPTURE_INACTIVE_PAYMENT
+ VOID_INACTIVE_PAYMENT
+ REFUND_MANUAL_PAYMENT
+ ORDER_WITHOUT_PRODUCTS
+ VARIANT_DOES_NOT_EXIST
+ ORDER_NO_SHIPPING_ADDRESS
+ ORDER_INVALID_SHIPPING_METHOD
+ PAYMENT_ERROR
+ PARTIAL_PAYMENT_NOT_ALLOWED
+ SHIPPING_METHOD_REQUIRED
+ POSITIVE_NUMBER_REQUIRED
+ DOES_NOT_EXIST
+ VALUE_ERROR
+ NON_BLANK_VALUE_REQUIRED
+ MISSING_VALUE
+ INCORRECT_VALUE
+ CANNOT_FETCH_TAX_RATES
+ GRAPHQL_ERROR
+ INVALID_FILE_TYPE
+ INVALID_STOREFRONT_URL
+ AUTHORIZATION_KEY_ALREADY_EXISTS
+ ATTRIBUTE_ALREADY_EXISTS
+ ATTRIBUTE_VALUES_NOT_UNIQUE
+ ATTRIBUTE_SLUG_BLANK
+ ATTRIBUTE_SLUG_ALREADY_EXISTS
+ ATTRIBUTE_BAD_VALUE
+ ATTRIBUTE_ALREADY_ASSIGNED
+ ATTRIBUTE_NON_ASSIGNABLE
+ ATTRIBUTE_CANNOT_BE_ASSIGNED
+ ATTRIBUTE_DISABLED_VARIANTS
+ MISSING_CONFIGURATION_FIELDS
+ VARIANT_NO_DIGITAL_CONTENT
+ PRODUCT_ALREADY_EXISTS
+ NOT_PRODUCTS_IMAGE
+ DEFAULT_SHIPPING_ZONE_ALREADY_EXISTS
+ MAX_LESS_THAN_MIN
}
type Fulfillment implements Node {
diff --git a/saleor/graphql/shipping/mutations.py b/saleor/graphql/shipping/mutations.py
index affd8b78e9..08d341491e 100644
--- a/saleor/graphql/shipping/mutations.py
+++ b/saleor/graphql/shipping/mutations.py
@@ -5,6 +5,7 @@ from ...dashboard.shipping.forms import default_shipping_zone_exists
from ...shipping import models
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.scalars import Decimal, WeightScalar
+from ..core.utils.error_codes import ShippingErrorCode
from .enums import ShippingMethodTypeEnum
from .types import ShippingMethod, ShippingZone
@@ -52,7 +53,12 @@ class ShippingZoneMixin:
if default:
if default_shipping_zone_exists(instance.pk):
raise ValidationError(
- {"default": "Default shipping zone already exists."}
+ {
+ "default": ValidationError(
+ "Default shipping zone already exists.",
+ code=ShippingErrorCode.DEFAULT_SHIPPING_ZONE_ALREADY_EXISTS,
+ )
+ }
)
elif cleaned_input.get("countries"):
cleaned_input["countries"] = []
@@ -129,9 +135,12 @@ class ShippingPriceMixin:
):
raise ValidationError(
{
- "maximum_order_price": (
- "Maximum order price should be larger than "
- "the minimum order price."
+ "maximum_order_price": ValidationError(
+ (
+ "Maximum order price should be larger than "
+ "the minimum order price."
+ ),
+ code=ShippingErrorCode.MAX_LESS_THAN_MIN,
)
}
)
@@ -145,9 +154,12 @@ class ShippingPriceMixin:
):
raise ValidationError(
{
- "maximum_order_weight": (
- "Maximum order weight should be larger than the "
- "minimum order weight."
+ "maximum_order_weight": ValidationError(
+ (
+ "Maximum order weight should be larger than the "
+ "minimum order weight."
+ ),
+ code=ShippingErrorCode.MAX_LESS_THAN_MIN,
)
}
)
diff --git a/saleor/graphql/shop/mutations.py b/saleor/graphql/shop/mutations.py
index 3cdcc6548b..ce2bf3ba23 100644
--- a/saleor/graphql/shop/mutations.py
+++ b/saleor/graphql/shop/mutations.py
@@ -9,6 +9,7 @@ from ..account.i18n import I18nMixin
from ..account.types import AddressInput
from ..core.enums import WeightUnitsEnum
from ..core.mutations import BaseMutation
+from ..core.utils.error_codes import CommonErrorCode
from ..product.types import Collection
from .types import AuthorizationKey, AuthorizationKeyType, Shop
@@ -129,7 +130,8 @@ class ShopFetchTaxRates(BaseMutation):
if not settings.VATLAYER_ACCESS_KEY:
raise ValidationError(
"Could not fetch tax rates. Make sure you have supplied a "
- "valid API Access Key."
+ "valid API Access Key.",
+ code=CommonErrorCode.CANNOT_FETCH_TAX_RATES,
)
call_command("get_vat_rates")
return ShopFetchTaxRates(shop=Shop())
@@ -185,7 +187,14 @@ class AuthorizationKeyAdd(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, key_type, **data):
if site_models.AuthorizationKey.objects.filter(name=key_type).exists():
- raise ValidationError({"key_type": "Authorization key already exists."})
+ raise ValidationError(
+ {
+ "key_type": ValidationError(
+ "Authorization key already exists.",
+ code=CommonErrorCode.AUTHORIZATION_KEY_ALREADY_EXISTS,
+ )
+ }
+ )
site_settings = info.context.site.settings
instance = site_models.AuthorizationKey(
@@ -219,7 +228,14 @@ class AuthorizationKeyDelete(BaseMutation):
name=key_type, site_settings=site_settings
)
except site_models.AuthorizationKey.DoesNotExist:
- raise ValidationError({"key_type": "Couldn't resolve authorization key"})
+ raise ValidationError(
+ {
+ "key_type": ValidationError(
+ "Couldn't resolve authorization key",
+ code=CommonErrorCode.DOES_NOT_EXIST,
+ )
+ }
+ )
instance.delete()
return AuthorizationKeyDelete(authorization_key=instance, shop=Shop())
diff --git a/saleor/payment/gateways/braintree/forms.py b/saleor/payment/gateways/braintree/forms.py
index 0dd5c8626b..55bc036f10 100644
--- a/saleor/payment/gateways/braintree/forms.py
+++ b/saleor/payment/gateways/braintree/forms.py
@@ -32,7 +32,7 @@ class BraintreePaymentForm(forms.Form):
"payment error",
"Unable to process transaction. Please try again in a moment",
)
- raise ValidationError(msg)
+ raise ValidationError(msg, code="payment_error")
return cleaned_data
def get_payment_token(self):