fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

后端500报错,如何捕获报错信息?

Open Sharang-heng opened this issue 1 year ago • 1 comments
trafficstars

class RetriableError extends Error { } class FatalError extends Error { }

fetchEventSource('/api/sse', { async onopen(response) { if (response.ok && response.headers.get('content-type') === EventStreamContentType) { return; // everything's good } else if (response.status >= 400 && response.status < 500 && response.status !== 429) { // client-side errors are usually non-retriable: throw new FatalError(); } else { throw new RetriableError(); } }, onmessage(msg) { // if the server emits an error message, throw an exception // so it gets handled by the onerror callback below: if (msg.event === 'FatalError') { throw new FatalError(msg.data); } }, onclose() { // if the server closes the connection unexpectedly, retry: throw new RetriableError(); }, onerror(err) { if (err instanceof FatalError) { throw err; // rethrow to stop the operation } else { // do nothing to automatically retry. You can also // return a specific retry interval here. } } }); 看了官网的实例,似乎没办法获取到后端500报错的body中的detail,打印看过onopen中的response,似乎也没有参数能直接获取到 而且我发现onopen不抛异常的话onerror是捕获不了请求500的错误

Sharang-heng avatar Jan 17 '24 10:01 Sharang-heng

看了官网的实例,似乎没办法获取到后端500报错的body中的detail,打印看过onopen中的response,似乎也没有参数能直接获取到

这个库的实现里面,会

  • 先去执行fetch,拿到response,
  • 把上一步拿到的response传给onopen去执行
  • 处理流数据
  • 依次执行onclose,dispose,resolve(这部分可以不用细究)
  • 上面的几个步骤都在try中执行,catch住错误后如果不是内部主动中断请求,就会执行你传入的onerror

所以你如果希望获取到后端500报错的body中的detail,直接在onopen中从response中拿到即可(前提是你说的这个detail后端返回体中存在,假如你说的是后端返回的错误信息,我理解应该直接await response.json()即可拿到)

而且我发现onopen不抛异常的话onerror是捕获不了请求500的错误

根据上面说的执行逻辑, 你需要在onopen中判断响应是否是500,是的话抛出,才能在onerror中去捕获到,onerror中不负责对响应进行校验

jaywhen avatar Jan 23 '24 12:01 jaywhen