Platform Operation Exception

Flutnet provides a simple way to implement your custom exceptions in order to propagate the errors to the Flutter module: if you want to handle your exceptions in Flutter code, you need to extend the class PlatformOperationException.

All your custom errors will be generated by the $ flutnet pack command for your flutter project.

 

Example

In this example we are going to define a custom LoginException, with a custom error code.

This error will be handled in Flutter.

 

Custom error definition

LoginException.cs

using Flutnet.ServiceModel;

namespace my.library
{
    // Error code
    [PlatformData]
    public enum LoginErrors
    {
        InvalidUsername,
        InvalidPassword,
        InvalidUsernameAndPassword,
    }

    // Custom error class
    public class LoginException : PlatformOperationException
    {
        public LoginErrors Error { get; set; }
    }
}

 

Throwing the error in a PlatformOperation

LoginService.cs

using Flutnet.ServiceModel;

namespace my.library
{
    [PlatformService]
    public class LoginService
    {
        [PlatformOperation]
        public void Login(string username, string password)
        {
           // When login fails           
            throw  new LoginException()
                {
                    Error = LoginErrors.InvalidPassword
                };            
        }
     }
}

 

In Flutter project you just wrap your platform call with a try/catch

import 'package:flutter/material.dart';

import 'package:my_library/my/library/login_service.dart';

 

// Somewhere in your Dart code....

 

// Reference to the xamarin login service

 final LoginService _loginService = LoginService("registration_key");

 try {

         // The best password ever ;-)

         await _loginService.login(username: "admin",  password: "admin");

 

 } on LoginException catch (ex) {

      // handle the LoginException error

 } on PlatformOperationException catch (pe) {

      // handle some other xamarin errors

 } catch (ex) {

      // handle some other errors

 }