Home > Software design >  How to implement try statement when sending http request?
How to implement try statement when sending http request?

Time:11-30

I want to create a login method to post http request. I use the following code to post user data into the server and get a response:

import 'dart:convert';
import 'dart:html';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../Services/baseHttp.dart' as base;

class Services {
  late var token = '';

  Future<http.Response> login(String username, String password) async {
    var url = base.BaseURL.loginUrl;
    Map data = {"username": username, "password": password};
    var body = json.encode(data);
    var response = await http.post(Uri.parse(url),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: body);

    print(response.statusCode);
    token = response.body;
    print(token);
    return response;
  }
}

I tried to use try catch inside the method:

Future<http.Response> login(String username, String password) async {
try {
    var url = base.BaseURL.loginUrl;
    Map data = {"username": username, "password": password};
    var body = json.encode(data);
    var response = await http.post(Uri.parse(url),
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        },
        body: body);

    print(response.statusCode);
    token = response.body;
    print(token);
    return response;
    } catch (e) {
      print(e);
    }
}

I want to send statusCode instead of print(e) when any exception is thrown. How can I do that?

CodePudding user response:

To check whether a response is valid, you can check the status code if it's equal to 200 like this:

 if (response.statusCode == 200){
// Do something
} else {
// Throw exception
}

Taking a look the official documentation. You will see the following:

Future<Album> fetchAlbum() async {
  final response = await http
      .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}
  • Related