# Copyright 2023 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Used by Django REST framework exception handling."""

import logging
import traceback

from rest_framework import status
from rest_framework.views import exception_handler

from debusine.server.views import ProblemResponse

logger = logging.getLogger(__name__)


def debusine_exception_handler(exc, context):
    """Return ProblemResponse based on exc, context."""
    rest_response = exception_handler(exc, context)

    status_code = getattr(
        rest_response, "status_code", status.HTTP_400_BAD_REQUEST
    )
    detail = getattr(exc, "detail", None)

    formatted_traceback = traceback.format_exc().replace("\n", "\\n")

    logger.error(
        "Server exception. status_code: %s detail: %s traceback: %s",
        status_code,
        detail,
        formatted_traceback,
    )

    return ProblemResponse(
        title="Error", detail=detail, status_code=status_code
    )
