setExceptionHandler method

Future<void> setExceptionHandler(
  1. Future<void> exceptionHandler(
    1. ChatException exception
    )?, [
  2. void onError(
    1. Object error
    )?
])

Sets the chat exception handler in case you want to intercept and display the errors coming from the chat on your own (instead of relying on the prebuild error banners).

The exceptionHandler is a function that receives the exception. Passing null will remove the previously set handler.

await _chatViewController?.setExceptionHandler((ChatException exception) async (
  print('Chat exception: $exception');
}, (error) {
  print('setExceptionHandler() error $error');
});

@param exceptionHandler A function that receives an ChatException when it happens. Passing null will remove the previously set handler. @param onError Optional error handler for catching exceptions thrown when listening for exceptions.

Implementation

Future<void> setExceptionHandler(
  Future<void> Function(ChatException exception)? exceptionHandler, [
  void Function(Object error)? onError,
]) async {
  if (exceptionHandler != null) {
    handleError(dynamic error) {
      onError?.call(error);
    }
    try {
      await _chatExceptionHandlerSubscription?.cancel();
    } catch (e) {
      //Not needed to handle
    }
    _chatExceptionHandlerSubscription = _chatEvent.receiveBroadcastStream().listen(
      (dynamic event) {
        try {
          LibraryEvent libraryEvent = LibraryEvent.fromJson(jsonDecode(event));
          if (libraryEvent.eventName == 'inAppChat.internal.exceptionReceived') {
            exceptionHandler(ChatException.fromJson(libraryEvent.payload));
          }
        } catch (error) {
          handleError(error);
        }
      },
      onError: (dynamic error) {
        handleError(error);
      },
      cancelOnError: false,
    );
  }
  await _channel.invokeMethod('setExceptionHandler', exceptionHandler != null);
}