简体   繁体   中英

Javascript structured error handling

I am developing my first Javascript app and I am trying to go object oriented. There is a basic closure that returns my primary object and every function I invoke rests in that object. Some pseudo code would look like this:

primary = (function(){
var object = {
     doSomething = function(){};
},  
return {intance:function(return object)}
});

//invocation
primary.instance().doSomething();

What I am trying to achieve is to attach an error handler function to my object , so that whenever there is an internal error, it is cought, and I don't have to wrap every function call in a try catch block.

I tried object.onerror but the error went on to window object . Maybe I am getting the concept wrong. I tried searching on Github for some simpler framework that includes structured error handling, but no luck. I am pretty familiar with this in PHP, but I haven't done this so far in Javascript. Can somebody show me an example how it is done right?

EDIT: I know that structured error handling goes further, I am just trying to get a root handler, so that no errors / exceptions can pass on to the window object

Dealing with the error event without a try catch block will halt the execution of your script (except for any asynchronous functions that have already been called).

You can suppress (non-ajax, non-syntax) errors by capturing them on document.body or a more specific object, and stop them being thrown to the user (or reaching the window object) by using e.preventDefault() or return false , and send them to a global/object handler (to inspect or log) by passing the event object as an argument - but any of those options will stop your script execution beyond the point of error. That's the main benefit of a try catch block, and as far as I know there is no way around that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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