Skip to content

Commit

Permalink
Release: 5.9.3
Browse files Browse the repository at this point in the history
### Changelog:
* Feature(backend): Added readable messages for IntegrityError.

See merge request vst/vst-utils!634
  • Loading branch information
onegreyonewhite committed Mar 14, 2024
2 parents bf146c8 + b9bc7fd commit 34d58f2
Show file tree
Hide file tree
Showing 10 changed files with 252 additions and 91 deletions.
9 changes: 9 additions & 0 deletions doc/backend.rst
Original file line number Diff line number Diff line change
Expand Up @@ -484,3 +484,12 @@ To integrate web push notifications in your VSTUtils project, follow these steps


By following these steps, you can fast integrate and utilize web push notifications in projects with VSTUtils.


Troubleshooting
----------------------------------

Vstutils makes some errors more readable for common users and provides special error codes for administration to simplify troubleshooting.

* ``VE100-VE199`` - Database related errors.
* ``VE100`` - Integrity error code. Used when ``django.db.utils.IntegrityError`` appears.
216 changes: 126 additions & 90 deletions doc/locale/ru/LC_MESSAGES/backend.po

Large diffs are not rendered by default.

17 changes: 17 additions & 0 deletions test_src/test_proj/migrations/0044_product_uniq_name_store.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.11 on 2024-03-13 07:54

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('test_proj', '0043_manufacturer_store_product_option_manufacturer_store_and_more'),
]

operations = [
migrations.AddConstraint(
model_name='product',
constraint=models.UniqueConstraint(fields=('name', 'store'), name='uniq_name_store'),
),
]
3 changes: 3 additions & 0 deletions test_src/test_proj/models/nested_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ class Product(BaseModel):

class Meta:
default_related_name = 'products'
constraints = [
models.UniqueConstraint(fields=['name', 'store'], name='uniq_name_store')
]
_nested = {
'options': {
'allow_append': True,
Expand Down
41 changes: 41 additions & 0 deletions test_src/test_proj/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5104,6 +5104,47 @@ def serializer_test(serializer):
generated_serializer = ModelWithBinaryFiles.generated_view.serializer_class()
serializer_test(generated_serializer)

def test_custom_exception_messages(self):
# Test nested model viewsets permissions.
store = Store.objects.create(
name='test'
)
manufacturer = Manufacturer.objects.create(
name='test man',
store=store
)

results = self.bulk([
{
'method': 'post',
'path': f'/stores/{store.id}/products/',
'data': dict(
name='test prod',
store=store.id,
price = 100,
manufacturer=manufacturer.id
)
},
{
'method': 'post',
'path': f'/stores/{store.id}/products/',
'data': dict(
name='test prod',
store=store.id,
price = 100,
manufacturer=manufacturer.id
)
},
])
self.assertEqual(results[0]['status'], 201)
self.assertEqual(results[1]['status'], 400)
self.assertEqual(
results[1]['data']['detail'],
'We encountered an issue with your submission due to duplicate or invalid data. Please check your entries '
'for any mistakes or duplicate information and try again. If the issue continues, please contact support '
'with the error code: VE100.'
)

def test_nested_views_permissions(self):
# Test nested model viewsets permissions.
store = Store.objects.create(
Expand Down
2 changes: 1 addition & 1 deletion vstutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
# pylint: disable=django-not-available
__version__: str = '5.9.2'
__version__: str = '5.9.3'
21 changes: 21 additions & 0 deletions vstutils/api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from django.http.response import Http404, FileResponse, HttpResponseNotModified
from django.db.models.query import QuerySet
from django.db import transaction, models
from django.db.utils import IntegrityError
from django.utils.functional import cached_property, lazy
from django.utils.http import urlencode
from rest_framework.reverse import reverse
Expand Down Expand Up @@ -66,6 +67,8 @@
logger = logging.getLogger(settings.VST_PROJECT)
http404_re_translate = re.compile(r"^No\s(.+)\smatches the given query.$", re.MULTILINE)

INTEGRITY_ERROR_CODE = 'VE100'


def _get_cleared(qs):
return getattr(qs, 'cleared', lambda: qs)()
Expand All @@ -89,6 +92,7 @@ def apply_translation(obj, trans_function):

def exception_handler(exc, context):
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
traceback_str: _t.Text = traceback.format_exc()
default_exc = (exceptions.APIException, djexcs.PermissionDenied)
serializer_class = ErrorSerializer
Expand Down Expand Up @@ -128,14 +132,31 @@ def exception_handler(exc, context):
elif isinstance(exc, djexcs.ValidationError):
if hasattr(exc, 'error_dict'): # nocv
errors = apply_translation(dict(exc), translate) # type: ignore
if all := errors.pop('__all__', None):
errors['other_errors'] = all
elif hasattr(exc, 'error_list'):
errors = {'other_errors': apply_translation(list(exc), translate)}
else: # nocv
errors = {'other_errors': apply_translation(str(exc), translate)}

data = {"detail": errors}
serializer_class = ValidationErrorSerializer
logger.debug(traceback_str)

elif isinstance(exc, IntegrityError):
data = {
"detail": apply_translation(
'We encountered an issue with your submission due to duplicate '
'or invalid data. Please check your entries for any mistakes or '
'duplicate information and try again. If the issue continues, '
'please contact support with the error code: {}.',
translate
).format(
INTEGRITY_ERROR_CODE
)
}
logger.error(f'{traceback_str} \n ERROR CODE: {INTEGRITY_ERROR_CODE} \n')

elif not isinstance(exc, default_exc) and isinstance(exc, Exception):
data = {
'detail': translate(str(exc)),
Expand Down
10 changes: 10 additions & 0 deletions vstutils/translations/cn.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@
'Scanner camera': '扫描相机',
'Not supported by this device': '该设备不支持',
'Allow using camera in browser': '允许在浏览器中使用相机',

# errors
(
'We encountered an issue with your submission due to duplicate '
'or invalid data. Please check your entries for any mistakes or '
'duplicate information and try again. If the issue continues, '
'please contact support with the error code: {}.'
): (
'由於資料重複或無效,我們在提交時遇到了問題。請檢查您的輸入是否有任何錯誤或重複訊息,然後重試。如果問題仍然存在,請聯絡支援人員並提供錯誤代碼:{}'
)
}

SERVER_TRANSLATION = {
Expand Down
12 changes: 12 additions & 0 deletions vstutils/translations/ru.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,18 @@
'Scanner camera': 'Сканирующая камера',
'Not supported by this device': 'Не поддерживается текущим устройством',
'Allow using camera in browser': 'Разрешите использование камеры в браузере',

# errors
(
'We encountered an issue with your submission due to duplicate '
'or invalid data. Please check your entries for any mistakes or '
'duplicate information and try again. If the issue continues, '
'please contact support with the error code: {}.'
): (
'Мы столкнулись с проблемой из-за повторяющихся или неверных данных. Пожалуйста, проверьте свои '
'записи на наличие ошибок или дублирующейся информации и повторите попытку. Если проблема '
'не исчезнет, обратитесь в службу поддержки, указав код ошибки: {}.'
)
}

SERVER_TRANSLATION = {
Expand Down
12 changes: 12 additions & 0 deletions vstutils/translations/vi.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,18 @@
'Scanner camera': 'Máy quét',
'Not supported by this device': 'Không được thiết bị này hỗ trợ',
'Allow using camera in browser': 'Cho phép sử dụng máy ảnh trong trình duyệt',

# errors
(
'We encountered an issue with your submission due to duplicate '
'or invalid data. Please check your entries for any mistakes or '
'duplicate information and try again. If the issue continues, '
'please contact support with the error code: {}.'
): (
'Chúng tôi đã gặp sự cố khi gửi dữ liệu của bạn do dữ liệu trùng lặp hoặc không hợp lệ. Vui lòng kiểm tra '
'các mục nhập của bạn xem có lỗi hoặc thông tin trùng lặp nào không và thử lại. Nếu sự cố vẫn tiếp diễn, '
'vui lòng liên hệ với bộ phận hỗ trợ kèm theo mã lỗi: {}.'
)
}

SERVER_TRANSLATION = {
Expand Down

0 comments on commit 34d58f2

Please sign in to comment.