In my django app, I have multiple places where I raise a specific custom exception DeserializationError. My goal is to show/redirect to a pretty page to show the user this error, including the error message, when this error is raised. Basically, a page that says something like
Something went wrong. Please contact webmaster#email.com.
Error: DeserializationError. Message: SomeModel, "somemodel", does not exist.
Would this even be possible? I've been trying to search for a solution but haven't been able to find anything yet.
Most likely such errors will return HTTP 500 server error.
In django you can write your own custom view to handle such cases and return your own page with the html that you like.
The 500 (server error) view explains writing server error views. There are more types of errors handled as explained on same page.
An option for handling HTTP 500 errors, add this to your Settings file,
handler500 = 'mysite.views.my_custom_error_view'
and in the view, you can render the "error page" using
HttpResponseNotFound('<h1>Page not found</h1>')
the server_error() view will be overridden by handler500.
Related
I have a web server using CherryPy. I would like for users to be redirected to the root page if they try and access a page which requires parameters to be entered. If a user were to try and directly access:
localhost:8080/page
they will get an error message which looks something like:
404 Not Found
Missing parameters: parameter1,parameter2,...
Instead of this, I would like the user to be redirected to:
localhost:8080/
I have tried to change cherrypy.config such that whenever a 404 occurs, it checks the error message and sees if the issue is missing parameters. If this is not the issue, I would like the default 404 page to be shown. My code looks like this:
cherrypy.config.update({'error_page.404': error_page_404})
with the function error_page_404:
def error_page_404(status, message, traceback, version):
if message.startswith('Missing parameters'):
raise cherrypy.HTTPRedirect('/')
else:
raise cherrypy.HTTPError(status, message)
but when I try to access
localhost:8080/page,
I get the following error:
404 Not Found
Missing parameters: parameter1,parameter2
In addition, the custom error page failed:
cherrypy._cperror.HTTPRedirect: (['http://127.0.0.1:8080/'], 303)
Any thoughts?
Thank you!
I've managed to make a workaround by returning HTML code that redirects to the root:
def error_page_404(status, message, traceback, version):
if message.startswith('Missing parameters'):
return """<meta http-equiv="Refresh" content="0; url='/'" />"""
else:
return f'<h2>404 Not Found</h2>\n' \
f'<p>{message}</p>'
While this works for my purposes, I can't help but feel there must be a more native way of doing this in cherrypy
I am building a web application that works as Web API server for our mobile and Electron app. I am trying to properly design our error handling too.
I use Django, Django Rest Framework for RESTful API implementation.
For psycopg2 errors, I get the following:
"column "unifiedidd" of relation "basicinformation" does not
exist\nLINE 1: INSERT INTO profile.basicinformation (unifiedidd,
firstname,...\n ^\nQUERY:
INSERT INTO profile.basicinformation (unifiedidd, firstname,
middlename, familyname, sex, birthdate) VALUES
('8f38f402-ddee-11ea-bfee-ead0fcb69cd9'::uuid, 'Lily Francis Jane',
'Luo Yi', 'Chao Fan', 'Male', '1990-03-20')\nCONTEXT: PL/pgSQL
function inline_code_block line 5 at SQL statement\n"
In my view file, I am catching these errors as such:
def post(self, request, *args, **kwargs):
try:
return Response({"message": "Cool"},status=http_200_OK)
except ProgrammingError as e:
return Response({"message": str(e)},status=http_500_INTERNAL_SERVER_ERROR)
except IntegrityError as e:
return Response({"message": str(e)},status=http_500_INTERNAL_SERVER_ERROR)
except Exception as e:
return Response({"message": str(e)},status=http_500_INTERNAL_SERVER_ERROR)
First thing I wanna confirm is, because of the content of the error, I assume it is not a good idea to output the whole thing right? Since it shows the actual query. This is useful but maybe for error logging for developer use only.
So I assume I need to output a custom message. But given that there are tons of errors that may be encountered and I think it's impossible to create a custom message for each of these errors, I am thinking to output just a wildcard error message such as `Unexpected error has been encountered. Please contact developer team."
But also, this wildcard error message does not seem so informative for both the developers and the users as well.
I am not sure how to properly handle exceptions and response it to the API client as informative as possible.
I have a Django app called chat and the root urls.py looks like this
path('messages/', include('chat.urls')),
However the url below, in the chat app urls.py is causing problems
re_path(r"^(?P<username>[\w.#+-]+)", login_required(chat_views.ThreadView.as_view()), name='thread'),
What is happening is that instead of throwing a 404 does not exist
error when I go to a made up url such as
localhost/messages/blahblah/02
It instead throws
NOT NULL constraint failed: chat_thread.second_id
Because it is assuming blahblah/02 is a username and is mapping it to the ThreadView which fails to get the thread object from 2 users.
So essentially, any other url pattern I try to create in the chat app doesn't route properly. (Example I tried creating a NotificationListView but couldn't access it due to routing messages/notifications to ThreadView)
How can I stop this from happening?
Using django 1.11, I have defined a custom 404 handler, by writing in my main URLs.py:
handler404 = 'myApp.views.myError'
The function myError() looks like this:
def myError(request):
#errorMsg=request.error_404_message
return render(request,'404.html')
This function works when I call raise Http404("My msg").
However, when I try to get the message passed by the Http404 call (see commented section in myError), my code crashes:
Server Error (500)
How can I then get the error message? I read a lot of questions about it like this one, but most answers refer to getting the message in the html file and not in a custom python error handler function.
EDIT: The problem is, that I cannot see the debug page, because the error obviously only occurs when myError() is called and this happens only, if debug=False in the settings.
The request does not have a error_404_message attribute by default, so request.error_404_message will give you an error.
The answer you linked to sets it as an attribute, but I do not see why you would want to do this in Django 1.9+, since you already have access to the exception in the view.
The signature of your custom view should be:
def myError(request, exception, template_name='404.html'):
...
You now have access to exception. You can look at the default page not found view to how it extracts the message from the exception.
When I go to www.keithirwin.us, my site works fine. But when I go to keithirwin.us without the prefix, I get a django 404 error ("Page not found at /").
Now since I get a django error and not my browser's "server not found" error, it must at least be pointing to my server. But the django error says "You're seeing this page because debug = True" and that's false! So who's django project is it?
This problem has really twisted my brain. I'm just about ready to call an exorcist.
Aha! The DEBUG = True was from mezzanine's local_settings.py. I still don't know why I'm getting a 404 but I can figure it out from here.