아래 서술되는 case 들은 monad 를 사용하기 위한 case를 가정한것입니다.
const someFunc = () =>{
try{
...
}catch(error){
...
return null
} // 또는 if 로 문제상황 확인 후 return null
return ...
}
const nullableRes = someFunc()
const otherFunc = (value) => {
if(value == null){
... do
}
do ...
}
const nullableRes = someFunc()
const res = otherFunc(nullableRes)
Invention of the null-reference a billion dollar mistake (Tony Hoare)
const someFunc = () =>{
try{
...
}catch(error){
...
throw new Error('some error occur, reason ...')
}
return ...
}
...
const otherFunction = () => {
try{
const res = someFunc()
}catch(error){
console.log(error.message)
... doSomthing()
}
...
}
const theOtherFunc = ()={
return ''
}
const otherFunction = () => {
try{
const res = someFunc()
}catch(error){
console.log(error.message)
... doSomthing()
}
theOtherFunc()
...
}
const otherFunction = () => {
try{
const res = someFunc()
theOtherFunc()
}catch(error){
console.log(error.message)
... doSomthing()
}
...
}
그냥 처음부터 다 try/catch 에 넣으면 되지 않음?
const main = (userId) => {
try{
const user = getUser(userId)
const parsedUser = parseUser(user)
const transformUser = transformUser(parseUser)
}catch(error){
console.log(error.message)
}
}
const main = (userId) => {
try{
const user = getUser(userId)
const parsedUser = parseUser(user)
const transformUser = transformUser(parseUser)
}catch(error){
console.log(error.message)
if(error.type == 'parseError'){
sendAlarm()
const user = getUser(userId)
const transformUser = transformUser(user)
}
...
}
}
와 같은 식으로 하던가 아니면 아예 code-block 을 분리하는 방법도 가능할 것이다.
const main = (userId) => {
let user;
try{
user = getUser(userId)
}catch(error){
...
}
try{
user = parseUser(user)
}catch(error){
sendAlarm()
...
}
try{
const transformUser = transformUser(user)
}catch(error){
...
}
}
const parseUser = (user){ // 더이상 error 가 throw 되지 않는다.
try{
...
}catch(error){
sendAlarm()
return user
}
}
const parseUser = (user, isNeedAlarm){
try{
...
}catch(error){
if(isNeedAlarm){
sendAlarm()
}
return user
}
}
const someOther = (userId)=>{
const user = getUser(userId)
const parsedUser = parseUser(user)
if(user.someAttr == parsedUser.someAttr){ // error 발생에 따른 같은 user 인지 확인 ...
console.log('error occur')
}
}
const parseUser = (user, isNeedAlarm){
try{
...
return {user:parsedUser, isSuccess:true}
}catch(error){
if(isNeedAlarm){
sendAlarm()
}
return {user:user, isSuccess:false}
}
}
const main = (userId) => {
try{
const user = getUser(userId)
const parsedUser = parseUser(user)
const transformUser = transformUser(parseUser)
}catch(error){
console.log(error.message)
}
}