Salma
Salma

Reputation: 1280

How to get custom error from dio in flutter?

I am trying to get the custom error coming from the backend but DIO gives me this error instead:

DioError [DioErrorType.RESPONSE]: Http status error [400]

Here's my code:

  @override
  Future<SignUpResponseModel> registerBuyer(BuyerModel user) async {
    final response = await api.dio.post('api/users/buyer', data: user.toJson());
    if (response.statusCode == 200) {
      return response.data.value;
    } else {
      final error =
          response.data.errors[0] ?? "Error";
      throw Exception(error);
    }
  }

Upvotes: 1

Views: 7522

Answers (2)

Paras Arora
Paras Arora

Reputation: 703

Handling Dio exceptions like a PRO

// dio call

            Future<Customer> getProfileData() async {
              Dio dio = Dio();
              var options = BaseOptions(baseUrl: "YOUR_BASE_URL", headers: {
                'Content-Type': 'application/json',
              });
              dio.options = options;
            
              try {
     
               var response = await dio.get("YOUR_END_POINTS");
                return Customer.fromJson(response.data);
              } on DioError catch (e) {
                 throw  DioExceptions.fromDioError(dioError: e, errorFrom: "getProfileData").errorMessage();
             // if you want to customize the error message
            //  int statusCode =  DioExceptions.fromDioError(dioError: e, errorFrom: "getProfileData").errorStatusCode();
            //  if(statusCode == 404)
            //  {
            //    throw "Incorrect Email Password";
            //  }
              }
            }

/// EXCEPTION HANDLER

                      import 'dart:convert';
                  import 'dart:developer';
                  
                  import 'package:dio/dio.dart';
                  import 'package:flutter/cupertino.dart';
                  
                  class DioExceptions implements Exception {
                    static late String message;
                    static int statusCode = -1;
                  
                    DioExceptions.fromDioError(
                        {required DioError dioError, required String? errorFrom}) {
                      //This will print error is Json format and colorful
                      _prettyPrintError(dioError: dioError, errorFrom: errorFrom);
                      switch (dioError.type) {
                        case DioErrorType.cancel:
                          message = "Request to API server was cancelled";
                          break;
                        case DioErrorType.connectTimeout:
                          message = "Connection timeout with API server";
                          break;
                        case DioErrorType.receiveTimeout:
                          message = "Receive timeout in connection with API server";
                          break;
                        case DioErrorType.response:
                          message = _handleError(
                            dioError.response?.statusCode,
                            dioError.response?.data,
                          );
                          statusCode = dioError.response?.statusCode ?? -1;
                          break;
                        case DioErrorType.sendTimeout:
                          message = "Send timeout in connection with API server";
                          break;
                        case DioErrorType.other:
                          if (dioError.message.contains("SocketException")) {
                            message = 'No Internet';
                            break;
                          }
                          message = "Unexpected error occurred";
                          break;
                        default:
                          message = "Something went wrong";
                          break;
                      }
                    }
                  
                    String _handleError(int? statusCode, dynamic error) {
                      switch (statusCode) {
                        case 400:
                          return 'Bad request';
                        case 401:
                          return 'Unauthorized';
                        case 403:
                          return 'Forbidden';
                        case 404:
                          return error['message'];
                        case 500:
                          return 'Internal server error';
                        case 502:
                          return 'Bad gateway';
                        default:
                          return 'Oops something went wrong';
                      }
                    }
                  
                    String errorMessage() => message;
                  
                    int errorStatusCode() => statusCode;
                  
                    void _prettyPrintError(
                        {required DioError dioError, required String? errorFrom}) {
                      debugPrint(
                          '\x1B[31m${"********************************************************"}\x1B[0m');
                      debugPrint('\x1B[31m${"🚨 ERROR exception from: $errorFrom"}\x1B[0m');
                      debugPrint(
                          '\x1B[31m${"🚨 ERROR it's status Code : ${dioError.response?.statusCode ?? -1}"}\x1B[0m');
                      try {
                        JsonEncoder encoder = const JsonEncoder.withIndent('  ');
                        String prettyprint = encoder.convert(dioError.response?.data ?? '');
                        debugPrint(
                            '\x1B[31m${"********************************************************"}\x1B[0m');
                        log("🕵️$errorFrom Error Response :\n$prettyprint", name: "Error");
                        debugPrint(
                            '\x1B[31m🕵️$errorFrom Error Response :\n$prettyprint", name: "Error"\x1B[0m');
                        debugPrint(
                            '\x1B[31m${"********************************************************"}\x1B[0m');
                      } catch (e) {
                        log("🕵️ $errorFrom Error Response :\n${dioError.response?.data ?? ''}",
                            name: "Error");
                        debugPrint(
                            '\x1B[31m${"********************************************************"}\x1B[0m');
                      }
                    }
                  }

And on Console you have coloured json enter image description here

Upvotes: 1

Salma
Salma

Reputation: 1280

The solution is to put on DioError in the catch block of the code. This way i'll be able to manage and access the custom error coming from the backend.

try {
      final response =
          await api.dio.post('api/users/buyer', data: user.toJson());
      if (response.statusCode == 200) {
        return response.data.value;
      } else {
        final error =
            response.data.errors[0] ?? "Error";
        throw Exception(error);
      }
    } catch (e) {
      if (e is DioError) {
        //This is the custom message coming from the backend
        throw e.response.data['errors'][0] ??
            "Error";
      } else {
        throw Exception("Error");
      }
    }
  }

Upvotes: 1

Related Questions