• Stars
    star
    4,531
  • Rank 9,407 (Top 0.2 %)
  • Language
    Python
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Pretty and useful exceptions in Python, automatically.

better-exceptions Travis

Pretty and more helpful exceptions in Python, automatically.

Example screenshot of exceptions

Usage

Install better_exceptions via pip:

pip install better_exceptions

And set the BETTER_EXCEPTIONS environment variable to any value:

export BETTER_EXCEPTIONS=1  # Linux / OSX
setx BETTER_EXCEPTIONS 1    # Windows

That's it!

Python REPL (Interactive Shell)

In order to use better_exceptions in the Python REPL, first install the package (as instructed above) and run:

$ python -m better_exceptions
Type "help", "copyright", "credits" or "license" for more information.
(BetterExceptionsConsole)
>>>

in order to drop into a better_exceptions-enabled Python interactive shell.

Advanced Usage

If you want to allow the entirety of values to be outputted instead of being truncated to a certain amount of characters:

import better_exceptions
better_exceptions.MAX_LENGTH = None

While using better_exceptions in production, do not forget to unset the BETTER_EXCEPTIONS variable to avoid leaking sensitive data in your logs.

Use with unittest

If you want to use better_exceptions to format unittest's exception output, you can use the monkey patch below:

import sys
import unittest
import better_exceptions

def patch(self, err, test):
    lines = better_exceptions.format_exception(*err)
    if sys.version_info[0] == 2:
        return u"".join(lines).encode("utf-8")
    return "".join(lines)

unittest.result.TestResult._exc_info_to_string = patch

Note that this uses an undocumented method override, so it is not guaranteed to work on all platforms or versions of Python.

Django Usage

In settings.py, add your new class to the MIDDLEWARE setting and update your logging configuration:

# ...

MIDDLEWARE = [
    # ...
    "better_exceptions.integrations.django.BetterExceptionsMiddleware",
]

# ...

from better_exceptions.integrations.django import skip_errors_filter

# if you don't want to override LOGGING because you want to change the default,
# you can vendor Django's default logging configuration and update it for
# better-exceptions. the default for Django 3.1.4 can be found here:
# https://github.com/django/django/blob/3.1.4/django/utils/log.py#L13-L63
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'skip_errors': {
            '()': 'django.utils.log.CallbackFilter',
            'callback': skip_errors_filter,
        }
    },
    'handlers': {
        'console': {
            'level': 'INFO',
            # without the 'filters' key, Django will log errors twice:
            # one time from better-exceptions and one time from Django.
            # with the 'skip_errors' filter, we remove the repeat log
            # from Django, which is unformatted.
            'filters': ['skip_errors'],
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django': {
            'handlers': [
                'console',
            ],
        }
    }
}

example output:

image

Troubleshooting

If you do not see beautiful exceptions, first make sure that the environment variable does exist. You can try echo $BETTER_EXCEPTIONS (Linux / OSX) or echo %BETTER_EXCEPTIONS% (Windows). On Linux and OSX, the export command does not add the variable permanently, you will probably need to edit the ~/.profile file to make it persistent. On Windows, you need to open a new terminal after the setx command.

Check that there is no conflict with another library, and that the sys.excepthook function has been correctly replaced with the better_exceptions's one. Sometimes other components can set up their own exception handlers, such as the python3-apport Ubuntu package that you may need to uninstall.

Make sure that you have not inadvertently deleted the better_exceptions_hook.pth file that should be in the same place as the better_exceptions folder where all of your Python packages are installed. Otherwise, try re-installing better_exceptions.

You can also try to manually activate the hook by adding import better_exceptions; better_exceptions.hook() at the beginning of your script.

Finally, if you still can not get this module to work, open a new issue by describing your problem precisely and detailing your configuration (Python and better_exceptions versions, OS, code snippet, interpreter, etc.) so that we can reproduce the bug you are experiencing.

License

Copyright Β© 2017, Josh Junon. Licensed under the MIT license.

More Repositories

1

color

🌈 Javascript color conversion and manipulation library
JavaScript
4,775
star
2

color-convert

Plain color conversion functions in JavaScript
JavaScript
746
star
3

color-string

Parser and generator for CSS color strings
JavaScript
214
star
4

tortellini

A really stupid INI file format for C++11
C++
137
star
5

tabs-are-better-than-spaces

They are. Don't fight it.
HTML
73
star
6

node-error-ex

Easy error subclassing and stack customization
CoffeeScript
62
star
7

arua-meta

Standards, RFCs and discussion of the Arua language
Vim Script
44
star
8

node-editor

Generic node editor web components
TypeScript
27
star
9

xopt

ANSI C command line options parser
C
22
star
10

node-man-api

Eases the generation of (proper) man pages
JavaScript
18
star
11

node-is-arrayish

Check if an object can be used like an Array
CoffeeScript
16
star
12

flexicon

A lightweight, regex-based lexer framework for Python
Python
12
star
13

node-simple-swizzle

Simply swizzle your arguments
CoffeeScript
11
star
14

terminfo

Parse the Terminfo database
JavaScript
8
star
15

pet

Dead simple HTTP requests
JavaScript
8
star
16

dot-dot-dash-demo

Quick demo for Dot Dot Dash
C++
7
star
17

arua.io

The Arua language website
HTML
6
star
18

xp

A regular expression search (and replace) command line tool
JavaScript
6
star
19

handler-agent

Zero-dependency (req,res) handler callback agent for use in client requests
JavaScript
6
star
20

casscade

Experimental Cassowary (Kiwi) constraint-based layouts using CSS layout worklets (Houdini layout API)
JavaScript
5
star
21

starfuse

Mount StarBound .pak files as regular directories
Python
4
star
22

scaly

Minimalistic, composable cache and database layering inspired by CPU caches
JavaScript
4
star
23

this-image-is

A Reddit bot that tells you what's in an image using neural networks.
Python
4
star
24

CaptainJack

[ABANDONED] The unofficial JACK audio device driver for OS/X
C
3
star
25

qunit

Super simple unit testing in C99
C
3
star
26

mds-lava

Lava mod for Mindustry
3
star
27

nesmap

Universal NES Map editor
CoffeeScript
3
star
28

node-smart-pipe

Pipe to standard input, cross platform
CoffeeScript
3
star
29

docopt.md

Keep your docopt configuration directly in your readme
JavaScript
2
star
30

node-high-order

Find the length of a UTF-8 glyph by its first byte
CoffeeScript
2
star
31

mds-ancients-units

ANCiENTS Mindustry Mod (Units pack)
JavaScript
2
star
32

factorio-hand-crank

Hand Crank mod for Factorio
Makefile
2
star
33

fugu

(this is a mirror, I didn't write this)
C++
2
star
34

s-storage

localStorage bindings for S.js
JavaScript
2
star
35

node-man-api-mdoc

MDoc macro extensions for man-api
JavaScript
2
star
36

node-backslash

Parse backslashed strings
JavaScript
2
star
37

bellingbot

Bellingcat discord bot
Python
2
star
38

sig-router

A URL/history API router for S.js and Surplus applications
JavaScript
2
star
39

cssquery

Simple object queries using CSS-like selector syntax. I don't recommend you actually use this.
Python
2
star
40

lucky-the-eclectus

My parrot in Discord bot format. Keeps you company; nothing more.
JavaScript
1
star
41

node-transform-domain

Transforms a value given a source and destination domain
JavaScript
1
star
42

match-file-tree

Lightweight regex based file tree traversal
JavaScript
1
star
43

node-find-api

Finds all of the API calls and docs in a source file
JavaScript
1
star
44

arua-bootstrap-2

The Arua bootstrap compiler
C++
1
star
45

libcopynes

Git mirror of libcopynes
C
1
star
46

Codicle

Just Learn.
CoffeeScript
1
star
47

node-ddb

Fixed-sized frame decoding for Node.js using ffmpeg
C++
1
star
48

test-repo

JavaScript
1
star
49

node-legos

Snap your streams together
JavaScript
1
star
50

node-require-with-globals

Safely require a module with a modified global object.
JavaScript
1
star
51

cbind

Real C-binding / argument injection (some seriously cool shit)
C
1
star
52

test-layout-api-bug

Blink engine Houdini Layout API + WebAssembly access violation reproduction
HTML
1
star
53

josh-manders-made-this

But not really.
1
star
54

beep-osx

"Hardware speaker" beep for OS X
Objective-C
1
star
55

eloquent

Make expressive APIs easily and cleanly
CoffeeScript
1
star
56

cassowary-playground

A playground for Cassowary constraints
Rust
1
star
57

mist

Mist build system
CoffeeScript
1
star
58

eslint-plugin-smelly

Find code patterns that might be code smell
JavaScript
1
star
59

mud-json

JSON driver for the Mud ORM
JavaScript
1
star
60

node-call-with-globals

Safely call a function with a modified global object.
JavaScript
1
star
61

lib-llvm-clang

LLVM.js/Clang.js dependencies for Codicle
1
star
62

node-abyss

Deep and asynchronous.
JavaScript
1
star
63

tap-dot-neo

Spiritual successor to `tap-dot`
JavaScript
1
star
64

prisoners-dilemma

Prisoners Dilemma simulator
C
1
star
65

clang-extra-npm

Installs `clang-tools-extra` for you.
Shell
1
star
66

eslint-plugin-wtf

Catch mistakes literally no developer should be making.
JavaScript
1
star
67

node-atomic-fs

Atomically perform file operations
CoffeeScript
1
star
68

did-they-seriously-rename-master

Oh my god what bullshit is this
1
star
69

riffusion-cli

Hacked together CLI for Riffusion. Please, please don't abuse this.
JavaScript
1
star
70

node-find-higher-file

Traverses a path to find a file in a higher directory
JavaScript
1
star
71

node-emplace

Emplace objects and arrays - pointer to pointer style!
CoffeeScript
1
star
72

node-has-module

Checks for the existence of a module
JavaScript
1
star
73

autotest

C/C++ unit testing on Linux as simple as writing functions
C
1
star
74

qix-.github.io

My portfolio site.
Roff
1
star
75

node-consumer-stream

Readline-like functionality that keeps track of line counts and properly handles final lines without trailing newlines
CoffeeScript
1
star
76

duplicant

Finds similar lines in a codebase and shows them as a heatmap in VSCode
Rust
1
star