HackSoftware / Django-Styleguide

Django styleguide used in HackSoft projects

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Global exception handler

rrhubenov opened this issue · comments

Hi guys, great style guide ♥️!

I just wanted to propose an addition to the exception handling in the APIs section.

Using mixins is a great way to minimize code duplication but that means that all the APIs must inherit from the same mixin every time. To optimize even further a global exception handler can be used as described here -> https://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling.

Using the code in the style guide, we can move the handle_exception method to another package and make some minor changes to the code.

from django.core.exceptions import ValidationError

from rest_framework.views import exception_handler
from rest_framework import exceptions as rest_exceptions

EXPECTED_EXCEPTIONS = {
    ValidationError: rest_exceptions.ValidationError
}


def handle_exception(exc, context):
    if isinstance(exc, tuple(expected_exceptions.keys())):
        drf_exception_class = EXPECTED_EXCEPTIONS[exc.__class__]
        drf_exception = drf_exception_class(get_error_message(exc))

        return exception_handler(drf_exception, context)

    return exception_handler(exc, context)

get_error_message is unchanged.

The last step is to register the exception handler:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'path.to.handler.handle_exception'
}

And voilà!

This has been tested on Python 2.7 and everything works as expected, would love the feedback!

Cheers!

P.S. Venco 🔝

@rrhubenov Thanks for the proposal! That's a smart approach. If you care to open up a PR and add this, it'd be great.

On the lines of global exception handler, I just merged #38 , where we use exactly that, to provide custom formatting for our exceptions. If you want, check it out & build on top of that idea.

One personal thing about the global exception handler: You may want to have the flexibility for certain APIs to use this scheme & for other APIs to have the normal behavior.

That's why we took the mixin approach, where you can extend an API, to provide the desired behavior.

Cheers

@rrhubenov We finally got to the exception handling & updated the styleguide accordingly - https://github.com/HackSoftware/Django-Styleguide#errors--exception-handling

Would love to have your opinion on that 🙏

(Closing for now, in case there's any new input, feel free to reopen)