Sunday, May 19, 2024
26
rated 0 times [  33] [ 7]  / answers: 1 / hits: 115952  / 15 Years ago, wed, september 16, 2009, 12:00:00

How would you implement different types of errors, so you'd be able to catch specific ones and let others bubble up..?



One way to achieve this is to modify the prototype of the Error object:



Error.prototype.sender = ;


function throwSpecificError()
{
var e = new Error();

e.sender = specific;

throw e;
}


Catch specific error:



try
{
throwSpecificError();
}

catch (e)
{
if (e.sender !== specific) throw e;

// handle specific error
}




Have you guys got any alternatives?


More From » error-handling

 Answers
4

To create custom exceptions, you can inherit from the Error object:


function SpecificError () {

}

SpecificError.prototype = new Error();

// ...
try {
throw new SpecificError;
} catch (e) {
if (e instanceof SpecificError) {
// specific error
} else {
throw e; // let others bubble up
}
}

A minimalistic approach, without inheriting from Error, could be throwing a simple object having a name and a message properties:


function throwSpecificError() {
throw {
name: 'SpecificError',
message: 'SpecificError occurred!'
};
}


// ...
try {
throwSpecificError();
} catch (e) {
if (e.name == 'SpecificError') {
// specific error
} else {
throw e; // let others bubble up
}
}

[#98683] Saturday, September 12, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;