Explorar el Código

修改网关错误处理,返回数据为json

asd123a20 hace 2 años
padre
commit
ff1140cf55
Se han modificado 2 ficheros con 31 adiciones y 18 borrados
  1. 0 1
      service-code/app/service/type.js
  2. 31 17
      service-gateway/app/controller/home.js

+ 0 - 1
service-code/app/service/type.js

@@ -30,7 +30,6 @@ class TypeService extends Service {
     }
   }
   async delete({ id }) {
-    console.log(id);
     assert(id, 'id不存在');
     try {
       const res = await this.model.findOne({ _id: id });

+ 31 - 17
service-gateway/app/controller/home.js

@@ -33,9 +33,13 @@ class HomeController extends Controller {
     const options = {
       method: requestMethod,
       data,
+      headers: {},
       'Content-Type': 'application/json',
       nestedQuerystring: true,
     };
+    if (method !== 'get_verification_code' && method !== 'upload' && method !== 'import') {
+      options.dataType = 'json';
+    }
     // 如果是文件上传
     if (method === 'upload' || method === 'import') {
       const stream = await this.ctx.getFileStream();
@@ -46,25 +50,35 @@ class HomeController extends Controller {
       options['Content-Type'] = 'multipart/form-data';
     }
     // 发送请求
-    const res = await this.ctx.curl(`${address}${path}`, options);
-    // 默认返回值
-    msg = res.data;
-    // 日志详情默认值
-    details = data;
-    result = '成功';
-    // 错误异常处理(返回值)
-    // 缺少字段检测返回asser
-    if (res.status === 500 && res.data.name === 'AssertionError') {
-      msg = { errcode: -1002, errmsg: res.data.message, data: '' };
-      details = res.data.message;
-      result = '失败';
-    }
-    // 异常抛出检测
-    if (res.status === 500 && (res.data.name === 'ValidationError' || res.data.name === 'CastError')) {
-      msg = { errcode: -1002, errmsg: '系统错误', details: res.data.message };
-      details = res.data.message;
+    let res;
+    try {
+      res = await this.ctx.curl(`${address}${path}`, options);
+      // 默认返回值
+      msg = res.data;
+      // 日志详情默认值
+      details = data;
+      result = '成功';
+      // 错误异常处理(返回值)
+      // 缺少字段检测返回asser
+      if (res.status === 500 && res.data.name === 'AssertionError') {
+        msg = { errcode: -1002, errmsg: res.data.message, data: '' };
+        details = res.data.message;
+        result = '失败';
+      }
+      // 异常抛出检测
+      if (res.status === 500 && (res.data.name === 'ValidationError' || res.data.name === 'CastError')) {
+        msg = { errcode: -1002, errmsg: '系统错误', details: res.data.message };
+        details = res.data.message;
+        result = '失败';
+      }
+    } catch (error) {
       result = '失败';
+      details = error;
+      msg = { errcode: -1002, errmsg: '系统错误', details: error };
+      console.log(error, 'error');
     }
+
+
     // 写日志
     await this.setLog({ agent, service, module, method, item, details: JSON.stringify(details), result, auth });
     // 默认返回状态 = 当前请求返回状态