Fra*_*ion 5 javascript promise es6-promise
我有一个包含多种服务和方法的 API。我想手动处理其中一些调用,例如,如果错误在某种程度上是预期的,则向用户显示有用的错误消息。
对于其余的调用,我想要一个“catch”的默认实现,它将发出一条消息,一些全局侦听器将处理并显示更通用的错误消息。
我发现另一个堆栈溢出帖子几乎给了我我想要的: Promises and generic .catch() statements
也就是说,默认捕获但重新抛出错误。问题是,如果我为某些特定服务实现自己的捕获,我不希望通用捕获启动,因为这将显示全局通用错误。
有没有办法让 catch 的默认实现被覆盖,如果 catch 是手动实现的?
例子:
let promise = pageService.getPage({pageId})
.then( (resp) => {} )
// on error, use the default catch
let promise = pageService.getPage({pageId})
.then( (resp) => {} )
.catch( (error) => { /* I want to handle the error, override the default error implementation */} )
Run Code Online (Sandbox Code Playgroud)
小智 2
据我所知,promise 在“先到先服务”的基础上工作,这意味着第一个注册其 catch 函数的人也将是第一个被调用的。
到目前为止,我能想到的唯一丑陋的解决方法是扩展正在处理的错误,以便我可以识别它是否已经被处理。如果我们以您之前的例子为例:
const pageService = {
getPage: (pageId) => {
return doStuff(). catch((error) => {
error.handled = false;
setTimeout(() => {
if(!error.handled) {
// do your default handling
}
)}, 1);
});
throw error; //Let possible other handlers first have their go
}
}
let promise = pageService.getPage({pageId})
.then( (resp) => {} )
// on error, use the default catch
let promise = pageService.getPage({pageId})
.then( (resp) => {} )
.catch( (error) => {
//handle the error here
error.handled = true;
})
Run Code Online (Sandbox Code Playgroud)