import logging
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework.views import set_rollback
from .response import JSONResponse

logger = logging.getLogger("django")


class APIException(Exception):
    def __init__(self, msg="服务异常", code=40000, status=200):
        self.msg = msg
        self.code = code
        self.status = status


def exception_handler(exc, context):
    """
    全局异常处理
    """

    response = drf_exception_handler(exc, context)

    # DRF无法处理
    if response is None:
        set_rollback()

        if isinstance(exc, APIException):
            return JSONResponse(
                code=exc.code,
                msg=exc.msg,
                status=exc.status
            )

        logger.error("Unhandled Exception", exc_info=True)
        return JSONResponse(code=50000, msg="服务器错误", status=200)

    # DRF异常统一包装
    set_rollback()

    if response.status_code == 401:
        return JSONResponse(code=40100, msg=response.data, status=200)

    if response.status_code in (400, 404):
        return JSONResponse(code=40000, msg=response.data, status=200)

    return response