我认为:
- 第二种方法是不能接受的。
- 它不会失败,因为服务器仍然会发送一个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