我应该在我编写的每个方法中使用错误处理吗?

问题描述:

I have two classes, MyFirstClass and MySecondClass. I created and object of MySecondClass in MyFirstClass.

And if there any kind of error occurred in MySecondClass how do I handle those error through try{}catch(/Exception $e){}

Let's assume that errors might occur because of below reasons,

  • Undefined Index of an Array
  • Undefined Variable
  • SQL Query Exception

Sample Code:

class MyFirstClass {

    public function index() {
        try {
            $mySecondClass = new MySecondClass();
            $mySecondClass->sampleMethod();
        } catch(\Exception $e) {
            error_log($e->getMessage(), 0);
            $this->doSomethingElse();
        }
    }
}

Should I use error handling in each method that I write? Please share your suggestions.

我有两个类,MyFirstClass和MySecondClass。 我在MyFirstClass中创建了MySecondClass的对象。 p>

如果在MySecondClass中发生任何类型的错误,我如何通过 try {} catch(/ Exception $ e)处理这些错误 {} code> p>

我们假设由于以下原因可能会发生错误, p>

  • 数组的未定义索引
  • 未定义的变量 li>
  • SQL查询异常 li> ul>

    示例代码: strong>

      class MyFirstClass {
     
     public function index(){
     try {
     $ mySecondClass = new MySecondClass(); 
     $ mySecondClass-> sampleMethod()  ; 
    } catch(\ Exception $ e){
     error_log($ e-> getMessage(),0); 
     $ this-> doSomethingElse(); 
    } 
    } 
    } 
       code>  pre> 
     
     

    我应该在每个编写的方法中使用错误处理吗? 请分享您的建议。 p> div>

Try/Catch/throw/log littered across methods and code is not a good practice. You should ask below questions when you think of this :

What specifically you going to do with that exception ? If answer is swallow, I would say you need to think twice. If state is corrupted because of swallowing exception in a catch block, then some method higher up in call stack might again throw exception - And now what to do with this exception ? Again same cycle ? It will lead you to a bigger mess soon.

You might sparingly want to follow the pattern of catching exception immediately when you really know you can do something with it (like swallow and retry in case of sql timeout exception) Also you might want to catch exception immediately in case when you want to capture more context specific details in log. In that case catch and re throw new exception wrapping original exception as inner exception.

So in short - its good to have exception handling/logging at application root level or service boundary level.

Having said that - at centralized location you can also configure what to do with specific types of exception. For example :

Bad Request exception thrown as part of data validation in business layer would simply return 400 bad request (in case of web application)

In case exception is of type SqlException - throw generic Exception to client with some tracking ID and log detailed exception to eventlog/db/application insight etc.

In case of any exception from external system in business layer - again send generic exception to client and send notification email to system providing external service.

These are just few examples and good practice around exception handling also implicitly promotes good design. For example: why not to have a safe guard to ensure argument passed to method is not null and throw ArgumentNullException rather than catching NullReferenceException and then capturing arguments value by having try/catch/log at method level.

I posted question around exception handling and logging good practices here. Please check it has good debate and discussion with various suggestions and good practices.