自定义异常消息:最佳做法 [英] Custom Exception Messages: Best practices

查看:134
本文介绍了自定义异常消息:最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道在创建异常消息时应该多少努力强制有用的调试信息,或者我应该相信用户提供正确的信息,还是将信息收集推迟到异常处理程序?

Wondering how much effort I should go to forcing useful debugging information when creating exception messages, or should I just trust the user to supply the right info, or defer the information gathering to an exception handler?

我看到很多人在做他们的例外,例如:

I see a lot of people people doing their exceptions like:

throw new RuntimeException('MyObject is not an array')

或扩展默认异常与自定义异常,更改异常的名称:

or extending the default exceptions with custom exceptions that don't do much but change the name of the exception:

throw new WrongTypeException('MyObject is not an array')

但是这并没有提供太多的调试信息...并且不强制执行任何形式的错误消息。所以你可能会得到完全相同的错误,产生两个不同的错误消息...例如数据库连接失败vs无法连接到db

But this doesn't supply much debugging info... and doesn't enforce any kind of formatting with the error message. So you could end up with exactly the same error producing two different error messages... eg "Database connection failed" vs "Could not connect to db"

当然如果它会冒泡到顶部,它会打印堆栈跟踪,这是有用的,但它并不总是告诉我需要知道的一切,通常我最终不得不开始拍摄var_dump()语句,以发现出了什么问题而在哪里...虽然这可能会被一些正常的异常处理程序所抵消。

Sure, if it bubbles to the top, it'll print the stack trace, which is useful, but it doesn't always tell me everything I need to know and usually I end up having to start shooting off var_dump() statements to discover what went wrong and where... though this could be somewhat offset with a decent exception handler.

我开始思考下面的代码,我在哪里要求异常的抛出者提供必要的参数以产生正确的错误消息。我想这可能是这样的:

I'm starting to think about something like the code below, where I require the thrower of the exception to supply necessary args to produce the correct error message. I'm thinking this might be the way to go in that:


  • 必须提供最低限度的有用信息

  • 产生一些一致的错误消息

  • 异常消息的模板全部位于一个位置(异常类),因此更容易更新消息...

但是我看到的缺点是它们更难使用(需要您查找异常定义),因此可能会阻止其他程序员使用提供的异常。 。

But I see the downside being that they are harder to use (requires you look up exception definition), and thus might discourage other programmers from using supplied exceptions...

我想对这个想法发表评论。最佳做法是一致,灵活的异常消息框架。

I'd like some comment on this idea, & best practices for a consistent, flexible exception message framework.

/**
* @package MyExceptions
* MyWrongTypeException occurs when an object or 
* datastructure is of the incorrect datatype.
* Program defensively!
* @param $objectName string name of object, eg "\$myObject"
* @param $object object object of the wrong type
* @param $expect string expected type of object eg 'integer'
* @param $message any additional human readable info.
* @param $code error code.
* @return Informative exception error message.
* @author secoif
*/
class MyWrongTypeException extends RuntimeException {
    public function __construct($objectName, $object, $expected, $message = '', $code = 0) {
        $receivedType = gettype($object) 
        $message = "Wrong Type: $objectName. Expected $expected, received $receivedType";
        debug_dump($message, $object);
        return parent::__construct($message, $code);
    }
}

....

/**
 * If we are in debug mode, append the var_dump of $object to $message
 */
function debug_dump(&$message, &$object) {
     if (App::get_mode() == 'debug') {
         ob_start();
         var_dump($object);
         $message = $message . "Debug Info: " . ob_get_clean();
    }
}

然后使用:

// Hypothetical, supposed to return an array of user objects
$users = get_users(); // but instead returns the string 'bad'
// Ideally the $users model object would provide a validate() but for the sake
// of the example
if (is_array($users)) {
  throw new MyWrongTypeException('$users', $users, 'array')
  // returns 
  //"Wrong Type: $users. Expected array, received string
}

我们可能会在自定义异常处理程序中做一些像nl2br这样的东西,使事情变得美好对于html输出。

and we might do something like a nl2br in a custom exception handler to make things nice for html output.

已阅读:
http://msdn.microsoft.com/en-us/library/cc511859.aspx#

还有没有提到任何这样的事情,所以也许这是一个坏主意...

And there is no mention of anything like this, so maybe it's a bad idea...

推荐答案

我强烈建议关于 Krzysztof的博客,并会注意到,在你的情况下你似乎试图处理他所说的使用错误。

I strongly recommend the advice on Krzysztof's blog and would note that in your case you seem to be trying to deal with what he calls Usage Errors.

在这种情况下,需要的不是一个新的类型来表示它,而是一个更好的错误信息造成它作为这样一个帮助函数:

In this case what is required is not a new type to indicate it but a better error message about what caused it. As such a helper function to either:


  1. 生成要放入异常的文本字符串

  2. 生成整个异常和消息

是需要的。

方法1更清晰,但可能会导致一些更详细的使用,相反的是,更简洁的语法交易更简洁。

Approach 1 is clearer, but may lead to a little more verbose usage, 2 is the opposite, trading a terser syntax for less clarity.

请注意,这些函数必须非常安全(它们永远不应该造成本身无关的异常),而不是强制在某些合理的用途中提供可选的数据。

Note that the functions must be extremely safe (they should never, ever cause an unrelated exception themselves) and not force the provision of data that is optional in certain reasonable uses.

通过使用这些方法之一,如果需要,可以更容易地将错误消息国际化。

By using either of these approaches you make it easier to internationalise the error message later if required.

最小的堆栈跟踪给你功能以及可能的行号,因此您应该专注于提供不容易解决的信息。

A stack trace at a minimum gives you the function, and possibly the line number, thus you should focus on supplying information that is not easy to work out from that.

这篇关于自定义异常消息:最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆