자바스크립트
javascript ERROR Handler Function 템플릿
YG - 96년생 , 강아지 있음, 개발자 희망
2022. 12. 16. 20:57
errorHandler
// 1번 방법
function errorHandler(tryFunc, errorFn) {
try {
tryFunc();
return true;
} catch (error) {
errorFn();
return false;
}
}
function errorHandler(tryFunc, catchFunc, nextFunc) {
try {
tryFunc();
return true;
} catch (error) {
Console.print(error.message);
catchFunc(nextFunc);
return false;
}
}
// 2번 방법
const inputErrorHandler = (validate, input) => {
try {
validate(input);
return true;
} catch ({ message }) {
Console.print(message);
return false;
}
};
// 3번 방법
const InputErrorHandler = (validate, catchFunc, nextFunc) => {
try {
validate();
return true;
} catch ({ message }) {
Console.print(message);
catchFunc(nextFunc);
return false;
}
};
module.exports = inputErrorHandler;
이용 방법
// 1번 방법
function carFn(){
const check = errorHandler(() => Validation.check(input), errorFn);
if (check) callback(input);
});
}
readCarName(callback) {
Console.readLine(MESSAGE.read_car_name, (input) => {
const check = errorHandler(() => carNameValidation.check(input), view.readCarName, callback);
if (check) callback(input);
});
}
// 2번 방법
InputView.readChallengeCommand((command) => {
const isValidCommand = inputErrorHandler(Validation.challengeCommand, command);
if (!isValidCommand) {
this.#requestChallengeCommand();
return;
}
this.#processChallengeCommand(command);
});
// 3번 방법
readChallengeCommand(callback) {
Console.readLine(`${GAME_MESSAGE.enforce}\n`, (command) => {
const check = InputErrorHandler(
() => Validation.challengeCommand(command),
InputView.readChallengeCommand,
callback
);
if (check) callback(command);
});
},