#coding=utf-8

from rest_framework.views import exception_handler
from rest_framework import serializers
from rest_framework.exceptions import AuthenticationFailed,NotAuthenticated
from jwt.exceptions import ExpiredSignatureError

from .exceptions import CustomError
from utils import response_error

import traceback

def custom_exception_handler(exc, context):
    message = ''
    errcode = None
    if isinstance(exc, CustomError):
        message = exc.get_error_msg()
    elif isinstance(exc, serializers.ValidationError):
        if isinstance(exc.detail, list):
            message = exc.detail[0]
        elif isinstance(exc.detail, dict):
            for key, value in exc.detail.items():
                if key != "error":
                    message += key+"错误:"
                message += value[0]
        else:
            message = list(exc.detail)[0]
    elif isinstance(exc, AuthenticationFailed) or isinstance(exc, ExpiredSignatureError):
        message = str(exc)
        errcode = 460
    elif isinstance(exc, NotAuthenticated):
        message = str(exc)
        errcode = 460
    else:
        traceback.print_exc()
        message = str(exc)

    return response_error(message, errcode=errcode)

