Skip to content

Instantly share code, notes, and snippets.

@Andrew-He
Last active March 3, 2020 12:13
Show Gist options
  • Save Andrew-He/4c0856ffa10bae5b2c233340fa38ca9f to your computer and use it in GitHub Desktop.
Save Andrew-He/4c0856ffa10bae5b2c233340fa38ca9f to your computer and use it in GitHub Desktop.
ts es6异常捕获装饰器
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
}
}
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