我認爲:
- 第二種方法是不能接受的。
- 它不會失敗,因爲服務器仍然會發送一個http響應。
- 讓我告訴你我做什麼在我的項目:
我的項目啓動時
,我總是預先添加的文件夾結構的頂部命名errors
模塊,首先,我會寫一個Exception基類從Exception
繼承,然後根據我的經驗寫出一些常見的異常類,如ObjectNotFound
,ValidationError
。當我認爲應該在代碼中引發一個異常時,我會使用這個模塊中的異常,當我發現需要處理的新異常時,我會在其中寫入一個新的異常。
然後這是如何處理它們的工作。當你正在使用Django,它很容易趕上通過中間件例外,你可以寫這樣的事情:
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
....
上面的代碼是怎麼做的異常處理在我的項目的總結,一般,這是關於準確的異常控制,適當的異常分類,當然「顯式優於隱式」的哲學。
=== UPDATE === 當談到如何應對阿賈克斯相應的響應,你可以使用新功能在jquery1.5 statusCode
:從jQuery文檔
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
:
當 響應具有相應的代碼時要調用的數字HTTP代碼和函數的映射。例如,下面將 警報時響應狀態是404
你應該標記其中一個答案是正確的,並且讚揚那些幫助你的答案。這是一個很好的習慣,如果你打算繼續使用這個網站,並給那些花時間回答你的人一個好姿態:) – Sid 2012-03-21 11:38:29
@Sid謝謝你的指導:)。我想我的問題還沒有完成答案(但我現在已經選擇了最好的答案)。真的很抱歉,但是我的名聲還不足以讓您滿意。 – kavinyao 2012-03-21 12:35:59
如果您的問題未得到完全解答,您無需選擇最佳答案。對不起並不意味着要衝你:) – Sid 2012-03-21 12:50:26