Error Class Javascript
Contents |
& Guides Learn the Web Tutorials javascript throw new error References Developer Guides Accessibility Game development ...more docs javascript error object properties Mozilla Docs Add-ons Firefox WebExtensions Developer ToolsFeedback Get Firefox help Get web development help javascript error get message Join the MDN community Report a content problem Report a bug Search Search Languages Català (ca) Deutsch (de) Español (es)
Javascript Custom Error Objects
Français (fr) Bahasa Indonesia (id) 日本語 (ja) 한국어 (ko) Polski (pl) Português (do Brasil) (pt-BR) Русский (ru) 中文 (简体) (zh-CN) 正體中文 (繁體) (zh-TW) Add a translation Edit Advanced Advanced History Print this article MDN Web technology For developers JavaScript JavaScript reference Standard built-in objects Error javascript exception object Your Search Results ariyankhan josephmcasey AlexanderFradiani fscholz mondwan SphinxKnight janosch-x davidchase Mingun shawnacscott Sheppy ethertank Nickolay evilpie trevorh teoli davidbourguignon secoif DomenicDenicola dgchurchill timemachine3030 Sevenspade Potappo Sephr Brettz9 Mgjbot Allanbonadio Ptak82 JustinLudwig Error In This Article SyntaxParametersDescriptionError typesPropertiesMethodsError instancesPropertiesStandard propertiesVendor-specific extensionsMicrosoftMozillaMethodsExamplesThrowing a generic errorHandling a specific errorCustom Error TypesSpecificationsBrowser compatibilitySee also The Error constructor creates an error object. Instances of Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions. See below for standard built-in error types. Syntax new Error([message[, fileName[, lineNumber]]]) Parameters message Optional. Human-readable description of the error. fileName Optional. The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor. lineNumber
Query Strings Readline REPL Stream String Decoder Timers TLS/SSL TTY UDP/Datagram URL Utilities V8 VM ZLIB GitHub Repo & javascript try catch Issue Tracker Mailing List Node.js v6.7.0 Documentation Index | View on
Javascript Error Class Doesn't Support Automation
single page | View as JSON Table of Contents Errors Error Propagation and Interception Node.js style
Javascript Array Class
callbacks Class: Error new Error(message) Error.captureStackTrace(targetObject[, constructorOpt]) Error.stackTraceLimit error.message error.stack Class: RangeError Class: ReferenceError Class: SyntaxError Class: TypeError Exceptions vs. Errors System Errors Class: System Error error.code https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error error.errno error.syscall Common System Errors Errors# Applications running in Node.js will generally experience four categories of errors: Standard JavaScript errors such as:
form of try..catch..finally try..catch..finally and return The throw statement A validator example Changes in the usage pattern Comparison Exception analysis and rethrow Summary Understanding exception http://javascript.info/tutorial/exceptions is important to object-oriented programming in general and JavaScript in particular. https://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/ Exceptions is a special, very powerful way to deal with errors. Check-first error handling Let's take a bad code as an example. Like this: nonexistant() In the example above, a non-existing variable is accessed. What should a program do in this case? The simple and very old javascript error concept is that the program dies. Let's say we want to evade that sorrowful happening. So, what to do in case when the variable may be undefined? The simple way is to check it. Something like that: if (window.func) { func() } There still may be an error if window.func is not a function. So we'll need to error class javascript check for it as well: if (typeof(func) == 'function') { func() } In the code above, typeof ensures that the variable exists and it is actually a function. Hopefully we performed all necessary checks to ensure that running func is safe. But what if it isn't? What if the func body has errors? Again, we want to handle the error, not let the script just die. And here the try..catch construct kicks in. The try..catch construct The try..catch approaches the error handling from another side. Instead of "check if all ok, then do" approach, we try then catch errors. A completely different way to handle errors which replaces the checking code. The function example would look like: try { func() } catch(e) { alert(e) } If an error occurs inside the try block, the control is passed to the catch(e) section. It's argument e is assigned to a special exception object which contains the information about what happened. The variable e contains an instance of Error object (or it's inheritant like
I got a lot of responses and follow-up questions, so I thought I'd continue the discussion by explaining a little more about how to throw your own errors. To review, the basic syntax is: throw new Error("message"); This works in all browsers and will display the error information in the same way it would any unintentional JavaScript error. The "message" string is stored in the message property of the object (which is what the browser uses to display the message). Periodically, I see people throwing errors by just providing the string, such as this: throw "message"; Doing so will cause an error to be thrown, but not all browsers respond the way you'd expect. Firefox, Opera, and Chrome each display an "uncaught exception" message and then include the message string. Safari and Internet Explorer simply throw an "uncaught exception" error and don't provide the message string at all. Clearly, this is suboptimal from a debugging point of view. Of course, you can throw any type of data that you'd like. There are no rules prohibiting specific data types: throw { name: "Nicholas" }; throw true; throw 12345; throw new Date(); The only thing to remember is that throwing any value will result in an error if it's not caught via a try-catch statement. Firefox, Opera, and Chrome all call String() on the value that was thrown to display something logical as the error message; Safari and Internet Explorer do not. The only surefire way to have all browsers display your custom error message is to use an Error object. ECMA-262, 3rd Edition actually specifies seven error object types. These are used by the JavaScript engine when various error conditions occur and can also be manually created: Error - base type for all errors. Never actually thrown by the engine. EvalError - thrown when an error occurs during execution of code via eval() RangeError - thrown when a number is outside the bounds of its range. For example, trying to create an array with -20 items (new Array(-20)). These occur rarely during normal execution. ReferenceError - thrown when an object is expected but not available, for instance, trying to call a method on a null reference. SyntaxError - thrown when the code passed into eval() has a syntax error. TypeError - thrown when a variable is of an unexpected type. For example, new 10 or "prop" in true. URIError - thrown when an incorrectly formatted URI string is passed into encodeURI, encodeURIComponent, decodeURI, or decodeURIComponent. Understanding that there are different types of errors can make it easier