ns_error_util.mm 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #import "base/ios/ns_error_util.h"
  5. #import <Foundation/Foundation.h>
  6. #include "base/check.h"
  7. #include "base/mac/scoped_nsobject.h"
  8. namespace base {
  9. namespace ios {
  10. namespace {
  11. // Iterates through |error|'s underlying errors and returns them in an array.
  12. NSArray* GetFullErrorChainForError(NSError* error) {
  13. NSMutableArray* error_chain = [NSMutableArray array];
  14. NSError* current_error = error;
  15. while (current_error) {
  16. DCHECK([current_error isKindOfClass:[NSError class]]);
  17. [error_chain addObject:current_error];
  18. current_error = current_error.userInfo[NSUnderlyingErrorKey];
  19. }
  20. return error_chain;
  21. }
  22. } // namespace
  23. NSError* GetFinalUnderlyingErrorFromError(NSError* error) {
  24. DCHECK(error);
  25. return [GetFullErrorChainForError(error) lastObject];
  26. }
  27. NSError* ErrorWithAppendedUnderlyingError(NSError* original_error,
  28. NSError* underlying_error) {
  29. DCHECK(original_error);
  30. DCHECK(underlying_error);
  31. NSArray* error_chain = GetFullErrorChainForError(original_error);
  32. NSError* current_error = underlying_error;
  33. for (size_t idx = error_chain.count; idx > 0; --idx) {
  34. NSError* error = error_chain[idx - 1];
  35. scoped_nsobject<NSMutableDictionary> user_info(
  36. [error.userInfo mutableCopy]);
  37. [user_info setObject:current_error forKey:NSUnderlyingErrorKey];
  38. current_error = [NSError errorWithDomain:error.domain
  39. code:error.code
  40. userInfo:user_info];
  41. }
  42. return current_error;
  43. }
  44. } // namespace ios
  45. } // namespace base