我正在尝试创建Django中间件,该中间件记录有关从视图中引发的异常的特定信息。我无法获得引发异常的行号。
具体来说,追溯的结尾显示File "<string>", line None
。这个"<string>"
来自哪里,为什么它显示行号None
?无论我通过测试还是通过浏览器窗口导航到/view_raises_exception/
,我都会得到相同的结果。我确信我可以通过我的process_exception()
方法挖掘追溯来获取行号,但我想知道为什么exception.lineno
没有给我我期望的结果。
我的设置:
查看:
def exception_view(request):
raise SyntaxError('Custom error message...')
的url:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^view_raises_exception/', views.exception_view),
url(r'^view_raises_no_exceptions/', views.no_exception_view),
]
中间件文件:
from django.http import HttpResponse
class ExceptionLoggingMiddleware(object):
def process_exception(self, request, exception):
name = type(exception).__name__
message = str(exception)
line_no = exception.lineno
print('***INSIDE PROCESS_EXCEPTIONS***')
print('Name:', name)
print('Message:', message)
print('Line Number:', line_no)
# return HttpResponse('Exception handled.')
服务器日志:
System check identified no issues (0 silenced).
September 09, 2016 - 22:58:40
Django version 1.9, using settings 'middlewares_library.settings'
Starting development server at http://0.0.0.0:8080/
Quit the server with CONTROL-C.
***INSIDE PROCESS_EXCEPTIONS***
Name: SyntaxError
Message: Custom error message...
Line Number: None
Internal Server Error: /view_raises_exception/
Traceback (most recent call last):
File "/home/ubuntu/.virtualenvs/env3/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/ubuntu/.virtualenvs/env3/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/ubuntu/workspace/middlewares_library/library/views.py", line 6, in exception_view
raise SyntaxError('Custom error message...')
File "<string>", line None
SyntaxError: Custom error message...
[09/Sep/2016 22:58:43] "GET /view_raises_exception/ HTTP/1.1" 500 68472
提前致谢!