发生500错误时给管理员发邮件[英] Emailing admin when a 500 error occurs

本文是小编为大家收集整理的关于发生500错误时给管理员发邮件的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在Python中发生500个错误时,我该如何发送电子邮件给管理员.

我正在使用的网络框架是"瓶子".

推荐答案

只需使用@error(code)装饰器来定义错误处理页面,例如:

from bottle import run, error, route

@error(500)
def handle_500_error(code):
  # add mail send code here
  return "Error message here"

@route("/test_500")
def cause_error():
  raise Exception

run()

只需导航到/test_500即可在Action

中看到它

您当然可以像其他任何页面一样使用模板作为错误页面.我不确定有错误处理程序时是否有办法获取内置的瓶错误页面.

编辑:

显然,如果您使用的是最新的瓶子v0.8,则应用@error装饰器的功能将作为参数而不是错误代码,而是在这里,然后使用一些适当的WSGI中间件来处理并发送电子邮件(例如, this ).

其他推荐答案

以下是瓶文档.

除bottle.HTTPError以外的所有未手动异常都会导致500个内部服务器错误响应,因此它们不会崩溃您的WSGI服务器.

从此判断,您需要抓住这些Exception,并编写代码以发送电子邮件给可能有关的任何人.您的代码将进入try块,您将为bottle.HTTPError异常提供一些代码,然后代码捕获所有其他发送所需电子邮件的其他Exception.

本文地址:https://www.itbaoku.cn/post/1975366.html

问题描述

How can I send an email to admin when a 500 error occurs, in python.

The web framework I'm using is 'bottle'.

推荐答案

Just use the @error(code) decorator to define an error handling page, like so:

from bottle import run, error, route

@error(500)
def handle_500_error(code):
  # add mail send code here
  return "Error message here"

@route("/test_500")
def cause_error():
  raise Exception

run()

Just navigate to /test_500 to see it in action

You can of course use a template for the error page just like with any other page. I'm not sure if there's a way to get the built-in bottle error page while having an error handler.

Edit:

Apparently if you're using the latest Bottle v0.8, the function to which you apply the @error decorator receives as a parameter not the error code, but an bottle.HTTPError object, which contains the exception and traceback.

Alternatively, you can set Bottle to not handle exceptions by setting bottle.app().catchall to False as described here, and then use some appropriate WSGI middleware to handle them and send the email (e.g. something like this).

其他推荐答案

The following is a line from the Bottle documentation.

All unhandled exceptions other than bottle.HTTPError will result in a 500 Internal Server Error response, so they won't crash your WSGI server.

Judging by this you would want to catch those Exceptions and write the code to send an email to whomsoever it may concern. Your code will go into the try block and you will have a some code for the bottle.HTTPError exception and then code to catch all other Exceptions which sends the desired email.