error
ハンドラーをトリガーします。毎回単純にステータス200を返し、JSON応答で「エラー」フィールドを使用することは確かに可能ですが(dm03514で提案されているように)、これは2つの理由で悪いです。errors
という名前のモジュールを事前に追加します。最初に、Exception
から継承する基本のExceptionクラスを記述し、次に、経験からObjectNotFound
、ValidationError
などの一般的なExceptionクラスをいくつか書き出します。コードで例外を発生させる必要があると思う場合は、このモジュールの例外を使用し、新しい種類の例外を処理する必要がある場合は、新しい例外を記述します。from youproject import errors
# categorize your exceptions
400_ERRORS = (errors.ValidationError, errors.ParametersMissing, )
403_ERRORS = (errors.AuthenticationError, )
404_ERRORS = (errors.ObjectNotFound, errors.ResourceNotExist, )
class ExceptionHandleMiddleware(object):
def process_exception(self, request, e):
# set status_code by category of the exception you caught
if isinstance(e, 400_ERRORS):
status_code = 400
elif isinstance(e, 403_ERRORS):
status_code = 403
elif isinstance(e, 404_ERRORS):
status_code = 404
else:
# if the exception not belone to any one you expected,
# or you just want the response to be 500
status_code = 500
# you can do something like write an error log or send report mail here
logging.error(e)
response_dict = {
'status': 'error',
# the format of error message determined by you base exception class
'msg': str(e)
}
if settings.debug:
# you can even get the traceback infomation when you are in debug mode
response_dict['traceback'] = traceback.format_exc()
# set header and return the response
....
statusCode
の新機能を使用できます。$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404
respons={}
response["error|ok"]
response["msg"]="User not found"
response["type"]=ERROR_TYPE # only applicable for errors
response_dict = {}
try:
# do action that could cause an error
except ExpectedError as e:
response_dict['success'] = False
response_dict['message'] e.msg # or custom message
return HttpResponse(json.dumps(repsonse_dict))
{"errors": "true", "messages": ["Error #1", "Error #2", "etc."]}