简体   繁体   English

如何处理异常记录

[英]How to handle exception logging

I have a complex web app that I am adding error logging to, I want to be able to log exceptions: 我有一个复杂的Web应用程序,正在向其中添加错误日志记录,我希望能够记录异常:

try{
//typically mysql queries but can involve PayPal api, Facebook api amongst others
        }
        catch($e){
            logger($e);
        }

Is it safe to assume $e will always be a string, if not is there a php function I can call which will always give me the string output of '$e', so that my logger can store the resulting output in my log table? 是否可以安全地假设$ e始终是一个字符串,如果没有,我可以调用一个php函数,该函数将始终为我提供字符串输出'$ e',以便记录器可以将输出结果存储在我的日志表中?

It's not c++, it's php that is why you need to throw either Exception object or instance of object that is subclass of Exception 不是c ++,而是php,这就是为什么您需要抛出Exception对象或Exception的子类对象的实例的原因

From PHP manual 从PHP手册

The thrown object must be an instance of the Exception class or a subclass of Exception. 抛出的对象必须是Exception类的实例或Exception的子类。 Trying to throw an object that is not will result in a PHP Fatal Error. 尝试抛出非对象,将导致PHP致命错误。

So that is why you always have access to Exception class methods for example: 因此,这就是为什么您始终可以访问Exception类方法的原因,例如:

  • final public string getMessage ( void ) //Gets the Exception message final public string getMessage(void)//获取异常消息
  • final public string getTraceAsString ( void ) //Gets the stack trace as a string final public string getTraceAsString(void)//以字符串形式获取堆栈跟踪

that is why you can use catch(Exception $e){ echo $e->getMessage();} to get message of exception or trace which are always string. 这就是为什么可以使用catch(Exception $e){ echo $e->getMessage();}来获取始终为字符串的异常消息或跟踪消息的原因。

If you want to pass Exception object you can extend Exception class and override __toString() method to fit your needs. 如果要传递Exception对象,则可以扩展Exception类并重写__toString()方法来满足您的需求。

You can also be interested in Setting Exception Handler 您也可能对设置异常处理程序感兴趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM