Last active
March 3, 2020 12:13
-
-
Save Andrew-He/4c0856ffa10bae5b2c233340fa38ca9f to your computer and use it in GitHub Desktop.
ts es6异常捕获装饰器
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Catch from './catched' | |
const getDataErrorHandler = (error, ctx) => { | |
ctx.errorMessage = error.message | |
} | |
class App { | |
errorMessage = '' | |
componentDidMount() { | |
this.getData(); | |
} | |
@Catch(getDataErrorHandler) | |
async getData() { | |
const data = await api.getData() // throws Error | |
return data | |
} | |
@Catch | |
wrongMethod() { | |
const a = 10 | |
a = 20 // throws TypeError | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Catch(localHandler) { | |
return function(target, key, descriptor) { | |
const originalMethod = descriptor.value | |
descriptor.value = async function(...args) { | |
try { | |
return await originalMethod.apply(this, args) | |
} catch (error) { | |
const { handler } = catchDecoratorStore | |
if (localHandler) { | |
localHandler.call(null, error, this) | |
} else if(handler) { | |
handler.call(null, error, this) | |
} else { | |
console.warn(error.message) | |
} | |
} | |
} | |
return descriptor | |
} | |
} | |
export default Catch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment