Javascript中的自定义错误对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript中的自定义错误对象相关的知识,希望对你有一定的参考价值。

  1. function ErrorConstructor(constructorName) {
  2. var errorConstructor = function(message, fileName, lineNumber) {
  3. // don't directly name this function, .name is used by Error.prototype.toString
  4. if (this == window) return new arguments.callee(message, fileName, lineNumber);
  5. this.name = errorConstructor.name;
  6. this.message = message||"";
  7. this.fileName = fileName||location.href;
  8. if (!isNaN(+lineNumber)) this.lineNumber = +lineNumber;
  9. else this.lineNumber = 1;
  10. }
  11. errorConstructor.name = constructorName||Error.prototype.name;
  12. errorConstructor.prototype.toString = Error.prototype.toString;
  13.  
  14. return errorConstructor;
  15. }
  16. Usage: ErrorConstructor([constructorName])
  17.  
  18. Note: If no constructorName is specified, the default of Error.prototype.name is used
  19.  
  20. Usage for generated error constructor: errorConstructor([message[, location[, lineNumber]])
  21.  
  22. Examples:
  23.  
  24. var SecurityError = ErrorConstructor("Security Error"),
  25. MarkupError = ErrorConstructor("(X)html Markup Error");
  26. //these will both throw a SecurityError starting with "Security Error on line 83:"
  27. var xss_error = "Possible XSS Vector
  28. JSON XHR response parsed with eval()
  29. Recommended fix: Parse JSON with JSON.parse";
  30. throw new SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
  31. throw SecurityError(xss_error, "/js/searchResultsJSONloader.js", 83);
  32. //these will both throw the following MarkupError:
  33. //"(X)HTML Markup Error on line 1: Invalid DOCTYPE"
  34. throw new MarkupError("Invalid DOCTYPE");
  35. throw MarkupError("Invalid DOCTYPE");

以上是关于Javascript中的自定义错误对象的主要内容,如果未能解决你的问题,请参考以下文章

Javascript中比较两个无序对象数组的自定义实现

控制台记录时如何截断(Node)JS错误对象中的自定义字段

将自定义javascript对象转换为json [重复]

Javascript / webpack:如何将目录中的所有json文件与文件的自定义循环连接起来

Zapier - Javascript错误的自定义函数行为

来自 javascript PageMethods 的自定义 C# 数据传输对象