If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Custom error routing in web2py is easy enough, but a few critical details are not obvious from the docs, including the fact that the original error codes are changed to 200 OK status codes. This recipe provides a complete solution that retains the original error codes.

 

Routes file (routes.py):

routes_onerror = [
    ('myapp/*', '/myapp/default/handle_error')
]

Controller ({app}/controllers/default.py):

def handle_error():
	""" Custom error handler that returns correct status codes."""
	
	code = request.vars.code
	request_url = request.vars.request_url
	ticket = request.vars.ticket

	if code is not None and request_url != request.url:	# Make sure error url is not current url to avoid infinite loop.
		response.status = int(code) # Assign the error status code to the current response. (Must be integer to work.)

	if code == '403':
		return "Not authorized"
	elif code == '404':
		return "Not found"
	elif code == '500':
		
		# Get ticket URL:
		ticket_url = "<a href='%(scheme)s://%(host)s/admin/default/ticket/%(ticket)s' target='_blank'>%(ticket)s</a>" % {'scheme':'https','host':request.env.http_host,'ticket':ticket}

		# Email a notice, etc:
		mail.send(to=['admins@myapp.com '],
					subject="New Error",
					message="Error Ticket:  %s" % ticket_url)
		
		return "Server error"
	
	else:
		return "Other error"
 

More Info:

 
 

Comments (0)


Hosting graciously provided by:
Python Anywhere