Better Exceptions is a library recommended by both the recent Python Weekly and Pycoders Weekly, which is used to display more friendly exception information.

The error above can be simplified to this form:

# coding:utf-8
request = "test test test"  # Get the data from the request
a, b, c, d = request.split()  # Processing data

# After running:
Traceback (most recent call last):
  File "exc.py", line 8, in <module>
      a, b, c, d = request.split()
ValueError: need more than 3 values to unpack

or this

# coding:utf-8
# Front-end ajax passed data, back-end processing
request_dict = {}
user_name = request_dict["user_name"]

# After running:
Traceback (most recent call last):
  File "exc.py", line 5, in <module>
      user_name = request_dict["user_name"]
KeyError: "user_name"

A simple scenario in the latter case is that, according to the previous logic, the code is fine, but after going online, this error will always be reported, why? No one can figure it out, they can only see what data the user has sent and how to see it. Print out the data sent by the client? Do you do this in production? (Of course, the best way is to use Sentry)

Well, this is the scene where Better Exceptions appear. The same code as above, addimport better_exceptions

# coding:utf-8
import better_exceptions

request = "test test test"  # Get the data from the request
a, b, c, d = request.split()  # Processing data

# After running:
Traceback (most recent call last):
  File "exc.py", line 8, in <module>
      a, b, c, d = request.split()
                   └ "test test test"    # Added content
ValueError: need more than 3 values to unpack

or this

# coding:utf-8
import better_exceptions

# Front-end ajax passed data, back-end processing
request_dict = {}
user_name = request_dict["user_name"]

# 运行后:
Traceback (most recent call last):
  File "exc.py", line 5, in <module>
      user_name = request_dict["user_name"]
                  └ {}
KeyError: "user_name"

How Better Exceptions Do It

From the above application scenario description, and the final result, it seems to be useful. However, for web frameworks like Django and Tornado, it&#39;s of little use. why?

Take a look at the implementation of Better Exceptions:

better_exceptions/__init__.py  The last few lines of code

def excepthook(exc, value, tb):
    formatted, colored_source = format_traceback(tb)

    if not str(value) and exc is AssertionError:
        value.args = (colored_source,)
    title = traceback.format_exception_only(exc, value)

    full_trace = u"Traceback (most recent call last):\n{}{}\n".format(formatted, title[0].strip())
    write_stream(full_trace)


sys.excepthook = excepthook  # The key is this

It mainly uses the excepthook method of the sys module. The description of this method is as follows:

ref: https://docs.python.org/2/library/sys.html#sys.excepthook

This function prints out a given traceback and exception to sys.stderr. When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.

It probably means that if the system throws an uncaught exception, the interpreter will call the sys.excepthook method, passing three parameters: the exception class (ValueError or KeyError, etc.), the exception instance, and the traceback object.

This means that you can handle uncaught exception handling by the system by overriding this method. However, in the framework (I only looked at the Django code and tested Tornado), it handles exceptions itself, so this way of hooking will not be triggered.

Seeing this, you may think, what&#39;s the use of this thing? The scenario I can think of is your own crawler, which can be used for scheduled execution. In addition, another function of introducing this library is that it can be used to learn several modules in Python, such as sys.excepthook, inspect, ast, TraceBack etc. the use of modules.

In addition, I mentioned Sentry twice above. Through this, you can also see how Sentry&#39;s Python client (Raven-Python) handles exceptions.

The installation of this library can be done directly with pip:

pip install better-exceptions

Related articles

django nginx Deployment

Upload complete django project files to the server sftp ftp lrzsz can upload files to the server, depending on yourself My django project is called yunwei, the main app is rabc and web, the whole project is put under /opt/ as follows: [root@test-code op

How to customize manage.py management commands

Before starting the Django service each time, we run python manage. py xxx administration command. We can actually also customize the manage command, which is useful for performing standalone scripts or tasks such as clearing caches, exporting user mailin