处理错误的表达

Handle a faulty expression

我正在检查这样的表达式:

predicateExpression = [NSPredicate predicateWithFormat:jsonExpression];

但是如果jsonExpression有问题,我会得到一个异常。处理这个问题的最佳方法是什么?目前有一个try/catch。有没有办法用 NSError 做到这一点?

Currently there is a try/catch. Is there a way to do this with NSError?

您可以向 NSPredicate 添加扩展,它复制现有方法并添加 NSError ** 参数。对于可变参数方法,这很棘手,但并非不可能,所以让我们使用 predicateWithFormat:

的变体之一
@interface NSPredicate (WithError)

+ (NSPredicate *) predicateWithFormat:(NSString *)format argumentArray:(nullable NSArray *)arguments error:(NSError **)error;

@end

该方法的实现只需要在self上用try/catch调用底层方法predicateWithFormat:argumentArray:。在 catch 子句中,如果传递的 error 不是 nil 构造一个合适的 NSError 值(如果您愿意,可以在 userInfo 字典中包含原始异常), 将其分配给 *error, return nil 也表示失败。如果没有异常发生 return NSPredicate 值。

您现在的方法不会抛出异常,并且 return 有一个 NSError 错误值。

HTH