If I have following
function ValidationException(nr, msg){
this.message = msg;
this.name = "my exception";
this.number = nr;
}
function myFunction(dayOfWeek){
if(dayOfWeek > 7){
throw new ValidationException(dayOfWeek, "7days only!");
}
}
Question is:
How can I catch this particular exception in catch block?
JavaScript does not have a standardized way of catching different types of exceptions; however, you can do a general catch and then check the type in the catch. For example:
try {
myFunction();
} catch (e) {
if (e instanceof ValidationException) {
// statements to handle ValidationException exceptions
} else {
// statements to handle any unspecified exceptions
console.log(e); //generic error handling goes here
}
}
Related
I am running a query to return some data
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
How do I check if resultSpec is undefined and if so throw and error and stop executing?
I have tried
return resultSpec || throw new Error() however get syntax errors when I try that.
Just use an if statement:
async function getIngress(namespace) {
try {
const result = await k8sIngressApi.listNamespacedIngress(namespace, true);
const resultSpec = result.body.items[0].spec;
if (!resultSpec) throw new TypeError('Spec is undefined');
return resultSpec;
} catch (e) {
throw new Error(e);
}
}
As mentioned by others, if you don't plan on doing any error handling in your catch block other than to simply rethrow the error, the try/catch is not necessary here, as you can just let whichever function that calls getIngress handle it
You don't need the try and catch statement if you're not handling errors in that function.
if (resultSpec == undefined) throw Error("The result is undefined")
I am not sure if this is right or wrong, but something deep inside me tells me that i am doing it wrong to have logic code on catch stm.
For ex my catch looks something like this:
try{
// do some stuff that throws some unexpected errors
}
catch (error) {
if (error?.graphQLErrors[0]) {
let msg = error.graphQLErrors[0].message
switch (msg) {
case 'limited':
// TODO:: handle
default:
window.location.href = "www.someurl.com";
}
}
Mainly I am thinking that catch stm usually should stay short and clean without logic on it that can cause another error or exception, what happens if the code inside catch throws some error?
It's just fine to have logic in your catch block, if the logic is there in order to handle or report the error. That's what catch blocks are for.
what happens if the code inside catch throws some error?
That's a new error. If you don't catch it, it will propagate to the caller, etc.
Example:
function example() {
try {
// "x" has no method `foo` so this causes an error:
"x".foo();
} catch (e) {
console.log(`Caught error in \`example\`: ${e.message}`);
// "y" has no method `bar` so this causes an error:
"y".bar();
}
}
function wrapper() {
try {
example();
} catch (e) {
console.log(`Caught error in \`wrapper\`: ${e.message}`);
}
}
wrapper();
Throwing errors intentionally from the catch block is a common practice in many places. You can wrap the original into one that can be better handled higher up or perhaps throw a more meaningful error
class MyError extends Error {
constructor(errorCode) {
super();
this.errorCode = errorCode;
}
}
function example() {
try {
// "x" has no method `foo` so this causes an error:
"x".foo();
} catch (e) {
throw new MyError(42);
}
}
function wrapper() {
try {
example();
} catch (e) {
if (e.errorCode === 42) {//specific
console.log(`I know what this error means: the flux capacitor is broken`);
} else {//generic
console.log(`Caught error in \`wrapper\`: ${e.message}`);
}
}
}
wrapper();
can I have logic code if else statements within catch statement?
Yes.
what happens if the code inside catch throws some error?
The error will propagate to the next try catch block.
I have error handling set up using try/catch blocks, which in its simplified form looks like this
try {
// .. Some application logic
try {
// .. some async api code
} catch (e) {
throw new Error("Api Error")
}
return true;
} catch (e) {
throw new Error("Unknown Error")
}
And the issue is, whenever I expect "Api Error" to be returned I get "Unknown Error" it seems like all errors are propagated to the outermost catch?
Is there a way to avoid this or another approach that allows for nested error handling?
In your code, check if exception is happening inside the first try block. If so, the inner try won't be executed.
try {
// .. Some application logic
// exception occurs here
// below code is not executed and the control is given to catch block
try {
//this did not execute
// .. some async api code
} catch (e) {
throw new Error("Api Error")
}
return true;
}
catch (e) {
//control came here
throw new Error("Unknown Error")
}
This is also a possible case:
try {
// .. Some application logic
// no exceptions occur here
// below code is executed
try {
//this did not execute
//exception here
// .. some async api code
} catch (e) {
//control came here and this threw APIerror
throw new Error("Api Error")
}
//this did not execute as the previous catch block raised another exception
return true;
}
catch (e) {
//control came here
throw new Error("Unknown Error")
}
Hope this helps :)
I am looking for a solution in which I can capture all the errors(handled/unhandled) logged in the browser console.
I am aware about window.onerror and also window.addeventlistener('error', function(){}).
The above code captures only unhandled errors. I need to capture handled errors also.
For example:
function foo() {
var x = null;
try {
x.a = "";
} catch (e) {
//Exception will be digested here.
}
var y = null
y.b = "";
}
window.onerror = function() {
//Write logic for the errors logged in console.
}
foo();
In the above example try catch is there, so I will get error only for variable y not x.
Is there any way to listen/capture the catch block?
Thanks
The reality is that if an exception is caught, then it isn't a problem because your code knows how to deal with it.
In other programming languages like Java it's always good practise to only catch exceptions you can handle, and to throw everything else further up the chain and/or map to a different exception that may be more useful further up the call stack.
For example:
function foo() {
var x = null;
try {
x.a = "";
} catch (e) {
//Exception will be digested here.
console.log("I am writing code here but still don't know how to proceed");
throw new CustomError("Something was wrong");
}
var y = null
y.b = "";
}
Try calling window.onerror manually. However, please reconsider changing your approach. This is extremely dirty.
window.onerror = function(msg, url, lineNo, columnNo, error) {
if (error === 'custom') {
console.log("Handled error logged");
return true;
}
console.log("unhandled error")
return false;
};
Example try/catch
var myalert = function() {
try {
console.log(f);
} catch (e) {
window.onerror('test',null,null,null,'custom');
}
console.log("Gets here");
}
https://fiddle.jshell.net/L29jv5fv/2/
I'm writing a mocha clone, because mocha is lacking certain features that I need. But when I am using existing assertion libraries, I'm unable to catch errors that are returned by them. Here is the code that runs the tests.
Tester.Test = function(name, test_function) {
this.name = name;
this.run = function(callback) {
try {
test_function(callback);
} catch (e) {
callback(e);
}
};
};
I've already tried using domain to catch the error, but it's still not working:
var d = domain.create();
d.on("error", function(err) {
cb(err);
});
d.run(function() {
test.run(cb);
});
I still keep getting an AssertionError (expected false to be true). Any tips?