Skip to content

Instantly share code, notes, and snippets.

@ax003d
Created October 13, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ax003d/cc70ee9ac92e9af07095 to your computer and use it in GitHub Desktop.
Save ax003d/cc70ee9ac92e9af07095 to your computer and use it in GitHub Desktop.
"""
Common JSON error response for RESTful APIs.
Usage:
1. define your own _ERROR_CODES
2. import and render errors
from errorcodes import render_errors
# some where you want to render errors
render_errors('BODY_JSON_INVALID', detail='detail error message')
author: ax003d@gmail.com
"""
import json
from django.http import HttpResponse
_ERROR_CODES = {
'BODY_JSON_INVALID': {
'status_code': 400,
'error_code': '5001',
'error_message': 'body json invalid'
}
}
def render_errors(error, detail=None):
err = _ERROR_CODES[error]
ret = {'error_code': err['error_code'],
'error_message': err['error_message']}
if detail:
ret['detail'] = detail
resp = HttpResponse(
json.dumps(ret),
status=err['status_code'],
mimetype='application/json')
return resp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment