Answer the question
In order to leave comments, you need to log in
js. Central error handling
Guys share your experience on how to properly handle exceptions in JS applications. My idea is to put the entire application in a try/catch block and centrally handle the exceptions that occur. Suppose an exception of this type is sent in some function of my application:
Accordingly, in the catch handler, the processing of the received exception is done:
In general, I would like to know any exception handling patterns, or hear good advice.
And please tell me which is better: to have only one try / catch block or many - at different levels?
Thank you.
throw {
code:304,
name: 'ErrorType'
msg:'Ошибка.....',
file:'*.js',
line:115,
func: function(){}
}
catch(o){
// Можно записать ошибку в БД
log(....);
// Вызвать функцию обработчик (если есть)
o.func();
.....
// Ну и т.д
}
Answer the question
In order to leave comments, you need to log in
No one will decide what is best for you.
Of course, you can and should have try/catch
at the highest level. And give it some useful behavior - write it to the log, display a beautiful window, etc., so as not to frighten the user with system messages.
This is the necessary minimum.
And then look deeper. What will the handler function give you inside the exception object? In many cases it is already useless; it is too far from the point of occurrence of the error to try to fix it (for example, call the code again with a default value, wait for the resource to be freed, etc., in short, some kind of while/try
).
Before each function call that might throw an exception, before each component entry, you have three options:
finally
code is needed. And where you can do something meaningful before completely falling off screaming into the log. try {
// ...
} catch (e) {
if (! e instanceof MyError) {
throw e;
}
// ...
}
try {
// ...
} catch (e if e instanceof MyError) {
// ...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question