On Github bdadam / JSErrorsTalk
try {
throw new Error('Something bad happened.');
}
catch(ex) {
console.log(ex.name); // Error
console.log(ex.message); // Something bad happened.
console.log(ex.stack); // Error: Something bad happened. at ...
}
finally {
console.log('Finally always wins.');
}
function trueOrFalse() {
try {
throw new Error('An error occured.');
}
catch(ex) {
return false;
}
finally {
return true;
}
}
console.log(trueOrFalse()); // ????
function trueOrFalse() {
try {
throw new Error('An error occured.');
}
catch(ex) {
return false;
}
finally {
return true;
}
}
console.log(trueOrFalse()); // true
warum gibt es finally überhaupt?Der Code in finally Block läuft auch wenn:
try{
setTimeout(function() {
throw new Error('An error occured.');
}, 100);
} catch(ex) {
console.log('An exception catched: ', ex);
}
Uncaught Error: An error occured.
function doSomethingAsync(onSuccess, onError) {
$.ajax(url, {
success: onSuccess,
error: onError
});
}
doSomethingAsync(
function() { console.log('success'); },
function() { console.log('error'); }
);
eine callback Funktion
fs.readFile('data.txt', function(errorOrNull, result) {
if (errorOrNull) {
// error handling
}
});
function doSomethingAsync(callback) {
$.ajax(url, {
success: function(data) { callback(null, data); },
error: function() { callback(new Error('Network error.')); }
});
}
doSomethingAsync()
.then(onFulfilled, onRejected)
.catch(function() { ... });
function doSomethingAsync() {
return new Promise(function(resolve, reject) {
$.ajax(url, {
success: function(data) { resolve(data); },
error: function() { reject(new Error('Network error')); }
});
});
}
try {
throw {};
throw "Error";
throw -1;
throw function() {};
} catch(ex) {
console.log(ex); // {} or "Error" or -1
}
throw new Error('Error message');
function throwsAnException() {
throw new Error('Something bad happened.');
}
try {
throwsAnException();
}
catch(ex) {
console.log(error.name); // Error
console.log(error.message); // Something bad happened.
console.log(ex.stack);
}
Error: Something bad happened. at throwsAnException (http://127.0.0.1:3000/:184:12) at http://127.0.0.1:3000/:188:6 at http://127.0.0.1:3000/:193:5 (index):191
zumindest das message Property einer Ausnahme setzen
throw new Error('Something bad happened.');
function add(x, y) {
if (isNaN(x) || isNaN(y)) {
throw new TypeError('Arguments must be numbers.');
}
}
function goToUrl(url) {
if (url.indexOf('example.com') < 0) {
throw new URIError('Argument must be a URI \
on the example.com domain.');
}
}
function checkAge(age) {
if (age > 150 || age < 0) {
throw new RangeError('A valid age must be specified.');
}
}
function MyError(message) {
this.message = message;
var stack = (new Error()).stack;
if (stack) { this.stack = stack; }
}
MyError.prototype = new Error();
MyError.constructor = MyError;
MyError.prototype.name = 'MyError';
try {
throw new MyError('Error message.');
} catch(ex) {
console.log(ex instanceof Error); // true
console.log(ex instanceof MyError); // true
}
z.B. in C#:
try {...}
catch (ArgumentException ex) { ... }
catch (FileNotFoundException ex) { ... }
try { ... }
catch(ex) {
if (ex instanceof URIError) { ... }
else if (ex instanceof TypeError) { ... }
else if (ex instanceof MyCustomError) { ... }
}
try {
myroutine(); // may throw some exceptions
}
catch (e if e instanceof TypeError) { ... }
catch (e if e instanceof RangeError) { ... }
catch (e) {
logMyErrors(e); // pass exception object to error handler
}
Handled exceptions: wir sind vorbereitet, dass der Code Exceptions werfen kann (TypeError, RangeError, falscher Userinput usw.).
Aber was passiert mit unerwarteten Fehlern? Wie z.B.: Programmfehler, Logikfehler oder fehlende Ressource (z.B. Netzwerkproblem)
window.onerror = function(message, url, lineNumber) {
// log error
};
var onError = window.onerror;
window.onerror = function(message, url, lineNumber) {
// log error
// then call the other event handler if any
onError && onError.apply(window, arguments);
};
window.addEventListener('error', function(errorEvent) {
console.log(errorEvent);
console.log(errorEvent.error);
console.log(errorEvent.error.message);
console.log(errorEvent.error.stack);
console.log(errorEvent.lineno);
});
window.onerror = function(message, url, lineNumber) {
_gaq.push([
'_trackEvent',
'JavaScript Error',
message,
url.indexOf('example.com/') > 0 ? 'internal' : 'external',
true
]);
};
window.onerror = function(message, url, lineNumber) {
var data = {
msg: message,
url: url,
internal: (url.indexOf('example.com/') > 0)
};
new Image().src = '/path/to/logger?data=' + JSON.stringify(data);
};