在我看来:
- 第二种方法不可接受。
- 它不会失败,因为服务器仍然会发送一个 http 响应。
- 让我告诉你我在项目中做了什么:
当我的项目开始时,我总是在文件夹结构的顶部预先添加一个名为errors的模块,首先我会编写一个继承自Exception的基本异常类,然后写出一些常见的异常类,如@ 987654323@, 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
....
上面的代码是我在项目中如何处理异常的总结,总的来说,它是关于准确的异常控制、正确的异常分类,当然还有“显式优于隐式”的理念。
===更新===
至于ajax中如何处理对应的响应,可以使用jquery1.5中的新特性statusCode:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
来自 jquery 文档:
数字 HTTP 代码和函数的映射,当
响应有相应的代码。例如,以下将
响应状态为 404 时发出警报