---
title: Record errors
source: https://docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile/mobile-sdk/record-errors
---

## iOS

### Syntax [#syntax]

#### Objective-c

```objectivec
recordError:(NSError* _Nonnull)error attributes:(NSDictionary* _Nullable)attributes;
```

#### Swift [#swift]

```swift
NewRelic.recordError(error: $Error, map $eventAttributes);
```

### Description [#description]

You can use the `recordError` API call for crash analysis. Review the captured events to help you understand how often your app is throwing errors and under what conditions. In addition to any [custom attributes](https://docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile/maintenance/add-custom-data-new-relic-mobile) that you added, the events will also have associated [session attributes](https://docs.newrelic.com/docs/insights/insights-data-sources/default-attributes/mobile-default-attributes-insights).

This API takes an instance of an error and an optional attribute dictionary, then creates a `recordHandledException` event. You can view event data in the mobile monitoring UI in places like the [**Handled exceptions** page](https://docs.newrelic.com/docs/mobile-monitoring/mobile-monitoring-ui/crashes/handled-exceptions-analyze-trends-prevent-crashes) and the [**Crash events** trail](https://docs.newrelic.com/docs/mobile-monitoring/mobile-monitoring-ui/crashes/mobile-crash-event-trail). You can also query this data with NRQL, and chart it in New Relic dashboards.

### Parameters [#parameters]

#### Objective-c

| Parameter                        | Type                                  | Description                                           |
| -------------------------------- | ------------------------------------- | ----------------------------------------------------- |
| `$error`, `error`                | `error`, `NSerror`                    | Required. The exception to be recorded.               |
| `attributes`, `$eventAttributes` | `NSDictionary`, `[AnyHashable, Any]?` | Optional. Dictionary of attributes that give context. |

### Examples [#examples]

#### Objective-C

Here's an example of a recording a simple error:

```objectivec
@try {
  @throw [NSException exceptionWithName:@"versionException"
                                 reason:@"App version no longer supported"
                               userInfo:nil];
} @catch (NSException* e) {
  [NewRelic recordHandledException:e];
}
```

Here's another example of recording an error with a dictionary:

```objectivec
[NSJSONSerialization JSONObjectWithData:data options:opt error:error];
if (error) {
  [NewRelic recordError:error
         withAttributes:@{@"int" : @1, @"Test Group" : @"A | B"}];
}
```

#### Swift [#swift]

Here's an example of a recording a simple error:

```swift
do {
    try method()
} catch {
    NewRelic.recordError(error)
}
```

Here's another example of recording an error with a dictionary:

```swift
do {
    try method()
} catch {
    NewRelic.recordError(error, attributes: [ "int" : 1, "Test Group" : "A | B" ])
}
```

## Cordova

### Syntax [#syntax]

```typescript
recordError(err: Error) : void;
```

### Description [#description]

Records JavaScript errors for Cordova. Make sure you add this method to the error handler of the framework that you are using.

### Examples [#examples]

#### Angular

Angular 2+ exposes an ErrorHandler class to handle errors. You can implement New Relic by extending this class as follows:

```typescript
import { ErrorHandler, Injectable } from '@angular/core';
import { NewRelic } from "@awesome-cordova-plugins/newrelic";

@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
  constructor() {
    super();
  }
  handleError(error: any): void {
    NewRelic.recordError(error);
    super.handleError(error);
  }
}
```

Then, you'll need to let Angular 2 know about this new error handler by listing overrides for the provider in app.module.ts:

```typescript
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },{provide: ErrorHandler, useClass: GlobalErrorHandler}],
  bootstrap: [AppComponent],
})
```

#### React

React 16+ has added error boundary components that catch errors that bubble up from child components. These are very useful for tracking errors and reporting errors to New Relic.

```typescript
import React, { Component } from "react";
import { NewRelic } from "@awesome-cordova-plugins/newrelic";

export class ErrorBoundary extends Component {
    componentDidCatch(error, errorInfo) {
        if (errorInfo && errorInfo.componentStack) {
            // Optional line to print out the component stack for debugging.
            console.log(errorInfo.componentStack);
        }

        NewRelic.recordError(error);
        this.setState({ error });
    }

    render() {
        // Render error messages or other components here.
    }
}
```

#### Redux

You can create [Redux Middleware](https://redux.js.org/tutorials/fundamentals/part-4-store#middleware) and apply it to your store. This will allow you to report any errors to New Relic.

```typescript
import { NewRelic } from "@awesome-cordova-plugins/newrelic";

const NewRelicLogger = store => next => action => {
    try {
        // You can log every action as a custom event
        NewRelic.recordCustomEvent("eventType", "eventName", action);
        return next(action)
    } catch (err) {

        //
        NewRelic.recordBreadcrumb("NewRelicLogger error", store.getState());

        // Record the JS error to New Relic
        NewRelic.recordError(err);
    }
}

export default NewRelicLogger;
```

Make sure that the middleware is applied when creating your store:

```typescript
import { createStore, applyMiddleware } from "redux"
import NewRelicLogger from "./middleware/NewRelicLogger"

const store = createStore(todoApp, applyMiddleware(NewRelicLogger));
```

#### Vue

Vue has a global error handler that reports native JavaScript errors and passes in the Vue instance. This handler will be useful for reporting errors to New Relic.

```js
import { NewRelic } from "@awesome-cordova-plugins/newrelic";

Vue.config.errorHandler = (err, vm, info) => {
    // Record properties passed to the component if there are any
    if(vm.$options.propsData) {
        NewRelic.recordBreadcrumb("Props passed to component", vm.$options.propsData);
    }

    // Get the lifecycle hook, if present
    let lifecycleHookInfo = 'none';
    if (info){
        lifecycleHookInfo = info;
    }

    // Record a breadcrumb with more details such as component name and lifecycle hook
    NewRelic.recordBreadcrumb("Vue Error", { 'componentName': vm.$options.name, 'lifecycleHook': lifecycleHookInfo })

    // Record the JS error to New Relic
    NewRelic.recordError(error);
}
```

## Capacitor

### Syntax [#syntax]

```typescript
recordError(options: { name: string; message: string; stack: string; isFatal: boolean; }) => void
```

### Description [#description]

Records JavaScript/TypeScript errors for Ionic Capacitor. Make sure to add this method to your framework's global error handler.

### Parameters [#parameters]

#### Objective-c

| Parameter | Type                                                                  | Description                                          |
| --------- | --------------------------------------------------------------------- | ---------------------------------------------------- |
| `options` | `{ name: string; message: string; stack: string; isFatal: boolean; }` | Required. An object that contains the error details. |

### Example [#example]

```typescript
try {
  throw new Error('Example error message');
} catch (e: any) {
  NewRelicCapacitorPlugin.recordError({
    name: e.name,
    message: e.message,
    stack: e.stack,
    isFatal: false,
  });
}
```

## Flutter

### Syntax [#flutter-syntax]

```dart
recordError(error, StackTrace.current, attributes: attributes);
```

### Description [#description]

You can register non-fatal exceptions using the `recordError` method with custom attributes.

### Example [#example]

```dart
try {
  some_code_that_throws_error();
} catch (ex) {
  NewrelicMobile.instance
    .recordError(error, StackTrace.current, attributes: attributes);
}
```

## React Native

### Syntax [#react-syntax]

```javascript
recordError(e: string|Error, isFatal?: boolean, attributes?: object): void;
```

### Requirements [#react-requirements]

-   [New Relic React Native agent](https://docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile-react-native/get-started/introduction-new-relic-react-native) installed and configured.
-   Call `NewRelic.setJSAppVersion()` at the start of your application so JavaScript errors can be captured.
-   Recording errors as `MobileJSError` events, the `isFatal` argument, and the `attributes` argument require React Native agent version 1.9.0 or higher. Earlier versions record these errors as `MobileHandledException` events.

    ### Description [#react-description]

    Use this call to record your app's handled or other miscellaneous JavaScript errors. This is useful when you have caught and handled an error, but you still want to identify it without disrupting your app's operation.

    These errors are recorded as [`MobileJSError` events](/attribute-dictionary/?event=MobileJSError). In addition to any [custom attributes](https://docs.newrelic.com/docs/mobile-monitoring/new-relic-mobile/maintenance/add-custom-data-new-relic-mobile) you add, the events also include associated [session attributes](https://docs.newrelic.com/docs/insights/insights-data-sources/default-attributes/mobile-default-attributes-insights). You can view this data in the mobile monitoring UI, query it with NRQL, and chart it in New Relic dashboards.

    ### Parameters [#react-parameters]

    | Parameter    | Type              | Description                                                                                                            |
    | ------------ | ----------------- | ---------------------------------------------------------------------------------------------------------------------- |
    | `e`          | `string`, `Error` | Required. The error to be recorded.                                                                                    |
    | `isFatal`    | `boolean`         | Optional. Whether the error is fatal. Defaults to `false`.                                                             |
    | `attributes` | `object`          | Optional. An object of name/value pairs of custom attributes that give the error additional context. Defaults to `{}`. |

    ### Examples [#react-examples]

    #### Record a handled error

    Here's an example of recording a caught error without disrupting your app:

```javascript
try {
  var foo = {};
  foo.bar();
} catch (e) {
  NewRelic.recordError(e);
}
```

#### Record an error from a promise rejection

Promises make it easy to overlook asynchronous errors. This example reports a rejected promise to New Relic so it isn't missed:

```javascript
fetch('https://api.example.com/data')
  .then(response => response.json())
  .catch(error => {
    // Report the unhandled rejection to New Relic
    NewRelic.recordError(error);
  });
```

#### Record a fatal error

Pass `true` as the second argument to mark the error as fatal:

```javascript
try {
  criticalOperation();
} catch (e) {
  NewRelic.recordError(e, true);
}
```

#### Record an error with custom attributes

Pass an attributes object as the third argument to add context to the error:

```javascript
try {
  var foo = {};
  foo.bar();
} catch (e) {
  NewRelic.recordError(e, false, { screen: 'Checkout', 'Test Group': 'A | B' });
}
```

## Unreal Engine

### Syntax [#syntax]

```cpp
recordError(FString errorMessage,TMap <FString, FString> errorAttributes);
```

### Description [#description]

Records errors for Unreal with Map Parameters .

| Parameter          | Type                    | Description                                                        |
| ------------------ | ----------------------- | ------------------------------------------------------------------ |
| `errorMessage`     | `FString`               | Required. The exception to be recorded.                            |
| `$errorAttributes` | `Map of String, String` | Optional. A map of attributes to be associated with the exception. |

### Example [#example]

```cpp
#include "NewRelicBPLibrary.h"

TMap<FString, FString> errorsMap;
errorsMap.Add("place", TEXT("Robots"));
errorsMap.Add("user", TEXT("Nisarg"));
UNewRelicBPLibrary::recordError(TEXT("Error Message"), errorsMap);
```

![Screenshot of the Unreal Engine Plugin Record Error](https://docs.newrelic.com/images/newrelic_unreal_sdk_record_error.webp "Unreal Engine Plugin Record Error")
