【问题标题】:Having an issue printing Rest request error in flutter在颤动中打印休息请求错误时出现问题
【发布时间】:2020-09-06 11:56:58
【问题描述】:

以下代码示例是从 Spring 服务器检索用户电子邮件的 GET 请求表单,当用户无效时抛出异常。

我无法从body含义中捕捉到错误的问题,如果我显式打印Body消息就可以看到。

目的是在细节有问题时查看错误信息给客户端

  Future<bool> fetchUser(username) async {

        setLoading(true);
        await RestRequest(username).fetchUser().then((data) {

          if (data.statusCode == 200) {
            setUser(User.fromJson(json.decode(data.body)));
            //print("got to ok code");
          }
          else{
           //print(data.headers.);
          }
     }
    ).catchError((error) {
      //TODO: handle errors
       errorMessage = jsonDecode(error.toString())["message"];
      throw(errorMessage);
    });

当我打印 data.body 时,我看到了错误。

 I/flutter (10871): {"timestamp":"2020-05-20T08:40:40.205+0000","status":500,"error":"Internal Server Error","message":"could not find user for email:a","trace":"acs.logic.EntityNotFoundException: could not find user for email:a\r\n\tat acs.logic.UserServiceWithDB.getUser(UserServiceWithDB.java:71)\r\n\tat acs.logic.UserServiceWithDB.login(UserServiceWithDB.java:79)\r\n\tat acs.logic.UserServiceWithDB$$FastClassBySpringCGLIB$$879f73c1.invoke(<generated>)\r\n\tat org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)\r\n\tat org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:687)\r\n\tat acs.logic.UserServiceWithDB$$EnhancerBySpringCGLIB$$647f71c3.login(<generated>)\r\n\tat acs.rest.UserController.login(UserController.java:29)\r\n\tat jdk.internal.reflect.GeneratedMethodAccessor71.invoke(Unknown Source)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.inv

FetchUser 函数

将'package:http/http.dart'导入为http;

class RestRequest {

   final String userEmail;
   final int port=8091;


  RestRequest(this.userEmail);


  Future<http.Response> fetchUser() {
    print(this.userEmail);
    return http.get('http://192.168.1.30:8091/acs/users/login/${this.userEmail}');
  }
}

【问题讨论】:

  • 你能添加你如何使用fetchUser的代码吗?您为此使用 FutureBuilder 吗?
  • 如果为 200,则必须解析 JSON 正文响应并检查是否 body["status"]==500 然后 print(body["error"])
  • 已编辑帖子
  • 看起来你在 Flutter 应用中有正确的代码,但是服务器返回了关于错误数据的消息。
  • 您好@aviomer,您能否检查一下您在 data.statusCode 中收到的值是多少?谢谢

标签: flutter dart


【解决方案1】:

我制作了一个工作示例来向您展示如何解析正文。 检查statusCode 200后,json解码“body”并查找字段“status”;如果是“500”,则获取“错误”字段:

import 'package:flutter/material.dart';
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final String body = """
  {"timestamp":"2020-05-20T08:40:40.205+0000","status":500,"error":"Internal Server Error","message":"could not find user for email:a","trace":""}
  """;

  Future<String> fetchUser(username) async {
    print("fetchUser");
    Map res = jsonDecode(body);

    print(res);
    if (res["status"] == 500) {
      return res["error"].toString();
    } else {
      //setUser(User.fromJson(json.decode(data.body)));
      return "got to ok code";
    }
  }

  @override
  Widget build(BuildContext context) {
    print("build");
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: FutureBuilder(
              future: fetchUser("Bill"),
              builder: (_, snap) {
                if (snap.hasData) return Text("${snap.data}");
                return Text("wait");
              }),
        ),
      ),
    );
  }
}

【讨论】:

  • Hello @aviomer 在你的情况下 (data.statusCode == 200) 是真还是假?
猜你喜欢
  • 2013-11-27
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 2021-01-19
  • 2020-01-25
  • 1970-01-01
  • 2015-06-13
  • 2021-05-28
相关资源
最近更新 更多