You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django接口中实现try-except,检索无效用户时返回Invalid user提示

Django视图添加无效用户异常处理实现

问题定位

原代码中customer = CustomerProfile.objects.get(user=pk)语句,当路径传入的pk匹配不到对应CustomerProfile记录时,Django ORM会直接抛出CustomerProfile.DoesNotExist异常,无捕获逻辑时会触发服务端500错误,无法返回自定义的"Invalid user"提示。

改造要点

  • 引入必要的DRF异常/响应组件,保证返回的错误信息符合接口交互规范
  • 用try-except块包裹用户查询逻辑,精准捕获用户不存在的异常,避免宽泛捕获所有异常掩盖其他代码问题
  • 触发无效用户场景时,终止后续的距离查询逻辑,直接返回携带"Invalid user"提示的响应

改造后完整代码

# 新增依赖导入
from rest_framework.response import Response
from rest_framework import status
from django.contrib.gis.geos import Point
from django.contrib.gis.measure import D
from Admin_Section.models import Distance

class ServiceProviderList(generics.ListAPIView):
    serializer_class = ProfilecompletioneSerializer
    filterset_class = SnippetFilter
    filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter]
    filterset_fields = ['fullname', 'category','departments','services']
    search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name']

    def get_queryset(self,*args, **kwargs): 
        pk = self.kwargs.get('pk')
        # 新增无效用户异常捕获逻辑
        try:
            customer = CustomerProfile.objects.get(user=pk)
        except CustomerProfile.DoesNotExist:
            return Response(
                {"detail": "Invalid user"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        Dist = Distance.objects.get(id=1)
        rad = float(Dist.distance)
        radius = rad / 111
        query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location, radius))
        return query

补充说明

  • 上述实现没有宽泛抓取所有类型的异常,只精准匹配CustomerProfile.DoesNotExist,保证其他代码bug可以正常抛出被日志记录
  • 可以选择更轻量化的异常实现方式:在捕获到用户不存在的异常时,直接抛出DRF内置的ValidationError("Invalid user"),无需手动构造Response对象,框架会自动按照统一错误格式返回提示
  • 如果需要提升代码健壮性,可将Distance.objects.get(id=1)的查询逻辑同步加入异常捕获,处理系统距离配置缺失的场景

内容的提问来源于stack exchange,提问作者surya raj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.28 00:36:05