Created
October 13, 2015 04:19
-
-
Save ax003d/cc70ee9ac92e9af07095 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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: [email protected] | |
""" | |
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