An expected error is one from the server that I anticipated or even raised by myself in the code. For example, when a user attempts to perform an action for which he has no sufficient privilege, I would raise PermissionError
(a custom Exception
) with a message describing the error.
I have been searching for a good way to handle expected error for AJAX situation. The only requirement is to be able to display the error message to the user, as I want to keep my users in the loop of what's going on.
My current approach is packaging the error message into a JSON object and send it back to the client-end
var ajaxResponse = $.ajax({
....
});
ajaxResponse.done(function(jsonObj) {
if (jsonObj.success) {
/* no error, do something */
}
else {
/* expected error returned, display jsonObj.error to user */
}
});
ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
/* unexpected error returned */
});
I have another approach in mind, which I am not sure about. Basically, instead of packaging the message of expected error into a JSON object, in my django code I would return HttpResponse(content="no sufficient privilege", status=403)
. The client-end jQuery would get modified like the following:
ajaxResponse.done(function(response_data) {
/* no error, do something */
});
ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
/* both expected and unexpected error would end up here.
* It's an expected error when error code is 403 and
* jqXHR.responseText would give me the error message to
* display to the user.
*/
});
I like how the second approach groups all errors, expected or unexpected, in one place. But then, I have a feeling that http status code shouldn't be used this way. Anyways, I want to know which one is the right way to go. If neither, please share what you would do.