0

I have an API which sends status 201 in case of a success and if there's any error with the submitted data it sends status 422 (Unprocessable Entity) with a JSON response.

{
"message": "The given data was invalid.",
"errors": {
    "mobile": [
        "The selected mobile is invalid."
    ]
}}

I am using Dio to post user credentials (mobile, password) if I enter the correct user credential I can fetch data from it but when I enter the wrong credential gives me this error:

Unhandled Exception: DioError [DioErrorType.response]: Http status error [422]

Dio code

    userLogin(
    String password,
    String mobile,
  ) async {
    try {
      String url = "url";

      Dio dio = Dio();

      dio.options.headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      };
      var response = await dio.post(url, queryParameters: {
        "password": password,
        "mobile": mobile,
      });
      if (response.statusCode == 200) {
        return response.data;
    } catch (e) {
      return e.toString();
    }}

How I cloud handle error response and success?

5 Answers 5

3

If some of Http status codes in responses are approved then you could use validateStatus function in BaseOptions to make them valid for all dio requests.

Dio dio = Dio(
    BaseOptions(
      headers: {...},
      validateStatus: (statusCode){
        if(statusCode == null){
          return false;
        }
        if(statusCode == 422){ // your http status code
          return true;
        }else{
          return statusCode >= 200 && statusCode < 300;
        }
      },
    )
);

or validateStatus function in Options of concrete request

var response = await dio.post(url, 
  queryParameters: {
    "password": password,
    "mobile": mobile,
  },
  options: Options(
    responseType: ResponseType.json,
    validateStatus: (statusCode){
      if(statusCode == null){
        return false;
      }
      if(statusCode == 422){ // your http status code
        return true;
      }else{
        return statusCode >= 200 && statusCode < 300;
      }
    },
  ),
);
Sign up to request clarification or add additional context in comments.

Comments

1

DioError [DioErrorType.response]: Http status error [422]

The Solution :)

Dio dio = Dio(
    BaseOptions(
      headers: {...},
      validateStatus: (statusCode){
        if(statusCode == null){
          return false;
        }
        if(statusCode == 422){ // your http status code
          return true;
        }else{
          return statusCode >= 200 && statusCode < 300;
        }
      },
    )
);

Comments

0

The catch method has to be added to the try. In your case it was added to if(response.statuscode ==200)

userLogin(
    String password,
    String mobile,
  ) async {
    try {
      String url = "url";

      Dio dio = Dio();

      dio.options.headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      };
      var response = await dio.post(url, queryParameters: json.encode({
        "password": password??"",
        "mobile": mobile??"",
      }));
      if (response.statusCode == 200) {
        return response.data;
      } 
     else{
       print(response.data);
       return "request failed";
       }
     }catch (e) {
      return e.toString();
    }

13 Comments

same Http status error [422] when I enter wrong credential it does not execute what its inside if (response.statusCode == 200) it jumps to catch error part
hope you are using the correct url and not the one written here.
yes I have the right one I test it with correct mobile and password it works fine
add a print statement just above if(response.statusCode == 200) print(response.data);
Error 422 means that your request is correct. Its just that the server is unable to process data that you have sent. Which I think how its handled by the backend. You can check if the statusCode == 422 and return something.
|
0

My Api response was this enter image description here

I have dealt with this method by allowing it BaseOptions here is my post API code and bingo got the solution to problem

Future postApiResponse(
          String url, dynamic data, bool tokentrue, String? token) async {
        dynamic responceJson;
        try {
          // print('here 222');
          if (kDebugMode) {
            print('In Dio in try');
            print(url);
            print(data.toString());
            print(tokentrue.toString());
            print(token.toString());
            print('In Dio in try');
          }
          Dio dio = Dio(BaseOptions(validateStatus: (statusCode) {
            if (statusCode == 422) {
              return true;
            }
            if (statusCode == 200) {
              return true;
            }
            return false;
          }));
          if (tokentrue == true) {
            // dio.options.headers['content-Type'] = 'application/json';
            dio.options.headers['Accept'] = 'application/json';
            dio.options.headers["authorization"] = "Bearer $token";
          } else {
            dio.options.headers['Accept'] = 'application/json';
          }
          // print('responceJson.toString()');
          Response responce = await dio
              .post(
                url,
                data: data,
              )
              .timeout(const Duration(seconds: 20));
    
          debugPrint('.toString()');
          responceJson = returnResponce(responce);
          debugPrint(responce.toString());
        } on DioError catch (e) {
          returnExceptionError(e);
        }
    
        return responceJson;
      }

Comments

0
//**Solution**
//Same other solutions but use new sdk version
//add this into dio instance
 validateStatus: (code) => switch (code.runtimeType) {
            int => code == 422 || '$code'.startsWith('2'),
            _ => false
          }));

//**Exception**
DioException [bad response]: The request returned an invalid status code of 422.
#0      DioMixin.fetch.<anonymous closure> (package:dio/src/dio_mixin.dart:507)
#1      _RootZone.runUnary (dart:async/zone.dart:1661)
#2      _FutureListener.handleError (dart:async/future_impl.dart:174)
#3      Future._propagateToListeners.handleError (dart:async/future_impl.dart:852)
#4      Future._propagateToListeners (dart:async/future_impl.dart:873)
#5      Future._completeError (dart:async/future_impl.dart:649)
#6      _SyncCompleter._completeError (dart:async/future_impl.dart:60)
#7      _Completer.completeError (dart:async/future_impl.dart:26)
#8      Future.any.onError (dart:async/future.dart:620)
#9      _RootZone.runBi`enter code here`nary (dart:async/zone.dart:1666)
#10     _FutureListener.handleError (dart:async/future_impl.dart:171)
#11     Future._propagateToListeners.handleError (dart:async/future_impl.dart:852)
#12     Future._propagateToListeners (dart:async/future_impl.dart:873)
#13     Future._completeError (dart:async/future_impl.dart:649)
#14     Future._chainForeignFuture.<anonymous closure> `enter code here`(dart:async/future_impl.dart:550)
#15     _microtaskLoop (dart:async/schedule_microtask.dart:40)
#16     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49)`enter code 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.