如何在不中止序列的情况下仅捕获特定类型的异常 [英] How to catch only specific type of exception without abort the sequence

查看:54
本文介绍了如何在不中止序列的情况下仅捕获特定类型的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

RxJs 似乎没有允许捕获特定类型异常的 catch() 方法的变体.但是很多时候我发现自己处于需要这样的操作员的境地.

RxJs does not seem to have a variation of catch() method which allow to capture only certain type of exception. But many times I found myself in a situation where such operator is needed.

例如,成像我需要解析日志文件的每一行并打印解析的消息.日志文件的某些行可能已损坏,但我真的不在乎,只想为该行输出日志消息已损坏"并继续下一行.

For example, imaging I need to parse each line of a log file and print the parsed message. Some lines of the log file might have been corrupted, but I really don't care and just want to output a "Log message corrupted" for such line and continue to the next line.

如果 catch() 确实允许我们指定特定类型的错误来捕获并传递所有其他错误,那么我们可以做一些类似下面的伪代码的事情

If catch() did allow us to specify a specific type of error to catch and pass through all other errors, we can then do some thing like pseudo-code below

readLogs()
.flatMap parseLog
.catchOnly ParseError, () ->
  'Log message corrupted'
.subscribe (logMessage) ->
  console.log logMessage

我想知道考虑到 catach() 的当前限制,RxJs 的正确方法是什么.

I was wondering what would be the proper way of RxJs to do that given the current limitation of catach().

推荐答案

您需要嵌套 catch 以防止错误终止整个链,并且您需要将逻辑分开分割解析行:

You would need to nest catch in order to prevent an error from terminating the entire chain and you would need to separate the logic for splitting and parsing lines:

import {of, throwError} from 'rxjs'
import {flatMap, map, catchError} from 'rxjs/operators'



function handleErrors(e) {
    return (e instanceof ParseError) ? 
            of("Log message corrupted") : throwError(e);
}

readLogs().pipe(
  flatMap(splitLines)
  flatMap(line => 
    of(line).pipe(
      map(parseLine), 
      catch(handleErrors)
    )
  )
)
.subscribe(
  parsedLine => console.log(parsedLine),
  e => console.error('Fatal error: ' + e);
);

这篇关于如何在不中止序列的情况下仅捕获特定类型的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆