<!--
{
  "availability" : [
    "iOS: 13.0.0 -",
    "iPadOS: 13.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.15.0 -",
    "tvOS: 13.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 6.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Combine",
  "identifier" : "/documentation/Combine/Publisher/mapError(_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Combine"
    ],
    "preciseIdentifier" : "s:7Combine9PublisherPAAE8mapErroryAA10PublishersO03MapD0Vy_xqd__Gqd__7FailureQzcs0D0Rd__lF"
  },
  "title" : "mapError(_:)"
}
-->

# mapError(_:)

Converts any failure from the upstream publisher into a new error.

```
func mapError<E>(_ transform: @escaping (Self.Failure) -> E) -> Publishers.MapError<Self, E> where E : Error
```

## Parameters

`transform`

A closure that takes the upstream failure as a parameter and returns a new error for the publisher to terminate with.

## Return Value

A publisher that replaces any upstream failure with a new error produced by the `transform` closure.

## Discussion

Use the [`mapError(_:)`](/documentation/Combine/Publisher/mapError(_:)) operator when you need to replace one error type with another, or where a downstream operator needs the error types of its inputs to match.

The following example uses a [`tryMap(_:)`](/documentation/Combine/Publisher/tryMap(_:)) operator to divide `1` by each element produced by a sequence publisher. When the publisher produces a `0`, the [`tryMap(_:)`](/documentation/Combine/Publisher/tryMap(_:)) fails with a
`DivisionByZeroError`. The [`mapError(_:)`](/documentation/Combine/Publisher/mapError(_:)) operator converts this into a `MyGenericError`.

```
struct DivisionByZeroError: Error {}
struct MyGenericError: Error { var wrappedError: Error }

func myDivide(_ dividend: Double, _ divisor: Double) throws -> Double {
       guard divisor != 0 else { throw DivisionByZeroError() }
       return dividend / divisor
   }

let divisors: [Double] = [5, 4, 3, 2, 1, 0]
divisors.publisher
    .tryMap { try myDivide(1, $0) }
    .mapError { MyGenericError(wrappedError: $0) }
    .sink(
        receiveCompletion: { print ("completion: \($0)") ,
        receiveValue: { print ("value: \($0)", terminator: " ") }
     )

// Prints: "0.2 0.25 0.3333333333333333 0.5 1.0 completion: failure(MyGenericError(wrappedError: DivisionByZeroError()))"
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)