Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: catch all errors and display the type of error and message

Tags:

django

I'm trying to make a generic error handler, something like "when others" in Oracle. The examples that I can find all involve catching a specific expected error.

Try:
    some_function()
Except: #I don't know what error I'm getting
    show_me_error(type_of_error_and_message)
like image 427
user984003 Avatar asked Oct 17 '11 08:10

user984003


People also ask

How do I show errors in Django?

The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. For example, here is the default error message: >>> from django import forms >>> generic = forms.

How do you catch a type of error in Python?

Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)

How do you print an error message in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

Is try catch Pythonic?

The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program's response to any exceptions in the preceding try clause.


1 Answers

This is very well-documented. But may be you just need Sentry?

try:
    1/0
except Exception as e:
    print('%s' % type(e))

>>> 
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)
like image 97
DrTyrsa Avatar answered Sep 20 '22 09:09

DrTyrsa