jax rs - constructing efficient error code mapper in Django filters or middlewares? -


i in process of migrating code jax-rs rest service django-rest framework. 1 nice feature jax-rs provides exception mapper different exceptions thrown various components mapped generic map one.

one example api call authenticate user can fail following reasons:

  1. username wrong -- error code 1000
  2. password wrong -- error code 1001
  3. database down - error code 1002

i might want map "1000" , "1001" 1 generic code "5325" front-end/device team can interpret "username , password did not match"

in jax-rs mapping done @ rest layer. in fact, can throw 1 kind of exception , map error code sent in response.

how can achieve same in django?

for example:

def process_checkout(request):     //     if request.user.is_authenticated :         //then process checkout     else:       raise usernotauthenticatederror 

now, middleware should map "usernotauthenticatederror" error-code, construct json response such {50000 :"user not authenticated"} , send response client.

thanks

django rest framework handles validation exceptions, other exception, through central exception handler. in django rest framework 3.0, validationerror exceptions make way exception handler, can relay them through there. in django rest framework 2.4, validation error handling done on serializer level, , have trigger errors there.

you need define exception handler in file (my.app.views) , set handler in django settings.

rest_framework = {     'exception_handler': 'my.app.views.exception_handler' } 

you need make sure set exception handler. situation-specific, following should started:

from rest_framework.exceptions import validationerror rest_framework.views import exception_handler  def custom_exception_handler(exc):     # call rest framework's default exception handler     # request work     response = exception_handler(exc)      if isinstance(exc, validationerror):         # return 422 status code validation errors        response.status = 422      return response 

in case, triggering new exception instead of changing status code of response.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -