Skip to content

Instantly share code, notes, and snippets.

@minrk
Created January 24, 2018 12:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/ea00729255cb269dffea214aacee2265 to your computer and use it in GitHub Desktop.
Save minrk/ea00729255cb269dffea214aacee2265 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"metadata": {},
"cell_type": "markdown",
"source": "# Polite error messages in IPython\n\nIPython allows registering a custom exception hook,\nwhich lets you do whatever you want when an error occurs.\n\nIf you want to hide the scary details of tracebacks for a bit,\nyou might use this.\n\nHere is an example showing a specific error message for NameErrors,\nand showing just the error message instead of a traceback for the rest.\n\nCareful! Eliminating the traceback can make it a lot harder to find where the mistake is."
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "def polite_errors(ip, etype, evalue, tb, tb_offset=None):\n if etype is NameError:\n print(\"Oops! looks like {}.\"\n \" Did you forget something or make a typo?\".format(evalue))\n # elif other special errors you can make nice\n else:\n # fallback on just error type and message (no traceback)\n print(\"%s: %s\" % (etype.__name__, evalue))\n \nget_ipython().set_custom_exc((Exception,), polite_errors)\n",
"execution_count": 1,
"outputs": []
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "undefined",
"execution_count": 2,
"outputs": [
{
"output_type": "stream",
"text": "Oops! looks like name 'undefined' is not defined. Did you forget something or make a typo?\n",
"name": "stdout"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "{}['a']",
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"text": "KeyError: 'a'\n",
"name": "stdout"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "1/0",
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": "ZeroDivisionError: division by zero\n",
"name": "stdout"
}
]
},
{
"metadata": {
"trusted": true
},
"cell_type": "code",
"source": "def foo()\n pass",
"execution_count": 4,
"outputs": [
{
"output_type": "stream",
"text": "SyntaxError: invalid syntax (<ipython-input-5-af92d274abf2>, line 1)\n",
"name": "stdout"
}
]
}
],
"metadata": {
"kernelspec": {
"name": "python3",
"display_name": "Python [default]",
"language": "python"
},
"language_info": {
"name": "python",
"version": "3.6.4",
"mimetype": "text/x-python",
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"pygments_lexer": "ipython3",
"nbconvert_exporter": "python",
"file_extension": ".py"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment