在方法的WebAPI在异常返回错误信息给最终用户 [英] Returning an error message to an end user upon exception in WebApi methods

查看:2741
本文介绍了在方法的WebAPI在异常返回错误信息给最终用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建设,与我的应用程序,允许用户点击一个按钮的触发一系列触发我一把umbraco网站与内容更新的Web服务请求的后台连接一个的WebAPI服务。

我的WebAPI服务类是设置为这样:

 公共类myController的:UmbracoApiController {
     //全局变量声明去这里     私人myController的(){
          //分配实际值的全局变量在这里
     }     公共字符串GetAllUpdates(){
          尝试{
              的getCountries();
              GetAreas();
              GetCities();
              ...
          }
          赶上(TimeoutException异常前)
          {
               Log.Error(Web服务超时,前);
               返回无法联系Web服务。
          }
          赶上(异常前)
          {
               Log.Error(异常,前);
               返回时发生错误。
          }
     }     公共字符串的getCountries(){
         尝试{
               //主code在这里
         }
         赶上(TimeoutException异常前){
           Log.Error(Web服务超时,前);
           返回无法联系Web服务。
         }
         赶上(例外前){
           Log.Error(异常,前);
           返回时发生错误。
         }
     }     .....
}

我的WebAPI方法是通过使用AngularJS和HTML的调用。当用户点击相关的网页API方法的按钮时,该方法在运行则消息被返回到在该方法的成功或失败的用户。

所以,如果我是运行的getCountries()使用相关按钮的消息方法将被显示在屏幕说:国家成功更新成功时或者相反,它会输出是在捕获返回的消息之一定义。

我的主要问题是,GetAllUpdates()方法运行所有的其它方法一前一后。这是不错,我成功时说:所有更新内容但安装真的分崩离析,当一个例外的其他方法之一被击中返回的消息。例如,的getCountries()首先运行。如果有异常这里提出,没有消息被返回到屏幕上,并应用简单地移到下一个方法GetAreas()。这种传播贯穿始终的地方则显示成功消息给用户一个错误的IM pression该更新进展顺利。

因此​​,我的问题是,我该如何停止GetAllUpdates()方法如果出现异常,而不修改我的其他方法回报链运行的后续方法?该方法需要返回,这样当他们对自己但是,当作为GetAllUpdates的一部分跑()返回在catch块的错误信息,如果该方法是完全成功的正在接受治疗的运行屏幕上显示的消息的字符串并且用户毫无收获。

任何帮助将大大AP preciated。

N.B。下面的回应之一下面我改变了我的WebAPI方法后执行下列操作:

类新

 公共类ResponseMessage
    {
        公共BOOL结果{搞定;组; }
        公共字符串消息{搞定;组; }
    }

回报方法

  ResponseMessage响应=新ResponseMessage();
            JSON字符串=的String.Empty;            response.Result = TRUE;
            response.Message =内容更新成功;            JSON = JsonConvert.SerializeObject(响应);
            返回JSON;

我的角code是如下:

  angular.module(一把umbraco)
.controller(AxumTailorMade
功能($范围,$ HTTP,AxumTailorMade){
    $ scope.getAll =功能(){
        $ scope.load = TRUE;
        $ scope.info =Retreiving更新;
        AxumTailorMade.getAll()。成功(功能(数据){
            变种响应= JSON.parse(数据);
            $ scope.result = response.Result;
            $ scope.info = response.Message;
            $ scope.load = FALSE;
        });
    };  });angular.module(umbraco.services)。工厂(AxumTailorMade功能($ HTTP){
    返回{
        GETALL:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getallupdates);
        },
        getRegions:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getregions);
        },
        的getCountries:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade /的getCountries);
        },
        getAreas:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getareas);
        },
        getCities:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getcities);
        },
        getCategories:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getcategories);
        },
        getPackages:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getpackages);
        },
        getHotels:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / gethotels);
        },
        getActivities:功能(){
            返回$ http.get(/一把umbraco / API / axumtailormade / getactivities);
        }
    };
})


解决方案

而不是返回从你的方法一个字符串,你能代替返回一个包含客户端的结果和消息的简单对象?

 公共类ResponseMessage
{
    公共BOOL结果{搞定;组; }
    公共字符串消息{搞定;组; }
}

在执行时,那么 GetAllUpdates()你会检查)的getCountries结果( GetAreas() GetCities()并追加任何错误消息。

 公共ResponseMessage GetAllUpdates()
{
    ResponseMessage响应;    响应=的getCountries();
    如果(!反应)
    {
        返回响应;
    }    响应= GetAreas();
    如果(!反应)
    {
        返回响应;
    }    响应= GetCities();
    如果(!反应)
    {
        返回响应;
    }    response.Result = TRUE;
    response.Message =成功;    返回响应;
}公共ResponseMessage的getCountries()
{
    VAR响应=新ResponseMessage();    尝试
    {
        //你的主要code在这里,请拨打服务等        response.Result = TRUE;
        response.Message =成功的getCountries;
    }
    赶上(TimeoutException异常前)
    {
        Log.Error(Web服务超时,前);
        response.Result = FALSE;
        response.Message =无法联系Web服务。
    }
    赶上(异常前)
    {
        Log.Error(异常,前);
        response.Result = FALSE;
        response.Message =发生了错误。
    }    返回响应;
}

这是多一点的努力,code,但也将让您在流动的返回给客户端什么更多的控制和。您还可以优化它了不少我敢肯定,我只是掐灭的一般方法为你...

I am currently building a WebApi service that connects with the backoffice of my application allowing the user to click a button an trigger a series of web service requests that trigger my Umbraco website to updated with content.

The class for my WebApi service is setup as so:

public class MyController : UmbracoApiController{
     // Global variable declarations go here

     private MyController(){
          // assign actual values to global variables here
     }

     public string GetAllUpdates(){
          try{
              GetCountries();
              GetAreas();
              GetCities();
              ...
          }
          catch (TimeoutException ex)
          {
               Log.Error("Web Service Timeout", ex);
               return "Failed to contact web services.";
          }
          catch (Exception ex)
          {
               Log.Error("Exception", ex);
               return "An error has occurred.";
          }
     }

     public string GetCountries(){
         try{
               // Main code here
         }
         catch(TimeoutException ex){
           Log.Error("Web Service Timeout", ex);
           return "Failed to contact web services.";
         }
         catch(Exception ex){
           Log.Error("Exception", ex);
           return "An error has occurred.";
         }
     }

     .....
}

My WebApi method are called through the use of AngularJS and HTML. When a user clicks the button related to a Web Api method, that method is run then a message is returned to the user upon success or failure of the method.

So, if I were to run the GetCountries() method using the relevant button a message would be displayed on the screen saying "Countries updated successfully" upon success or instead it would output one of the messages that are returned in the catch definitions.

My main problem is that the GetAllUpdates() method runs all of the other methods one after the other. This is fine and I return a message upon success saying "All content updated" however the setup really falls apart when an exception is hit in one of the other methods. For example, GetCountries() is run first. If an exception is raised here, no message is returned to the screen and the application simply moves onto the next method GetAreas(). This propagates through to the end where the success message is then displayed giving the user a false impression that the update went well.

My question therefore is how do I halt the GetAllUpdates() method from running subsequent methods in the chain if an exception occurs without modifying the returns in my other methods? The methods need to return a string so that the message is displayed on screen when they are run on their own however when ran as part of GetAllUpdates() the error messages being returned in the catch blocks are being treated as if the method was completely successful and the user is none the wiser.

Any help would be greatly appreciated.

N.B. After following one of the responses below I altered my WebApi method to do the following:

NEW CLASS

public class ResponseMessage
    {
        public bool Result { get; set; }
        public string Message { get; set; }
    }

RETURN ON METHODS

            ResponseMessage response = new ResponseMessage();
            String json = string.Empty;

            response.Result = true;
            response.Message = "Content update successful";

            json = JsonConvert.SerializeObject(response);
            return json;

My Angular code is as follows:

 angular.module("umbraco")
.controller("AxumTailorMade",
function ($scope, $http, AxumTailorMade) {
    $scope.getAll = function() {
        $scope.load = true;
        $scope.info = "Retreiving updates";
        AxumTailorMade.getAll().success(function (data) {
            var response = JSON.parse(data);
            $scope.result = response.Result;
            $scope.info = response.Message;
            $scope.load = false;
        });
    };

  });

angular.module("umbraco.services").factory("AxumTailorMade", function ($http) {
    return {
        getAll: function () {
            return $http.get("/umbraco/api/axumtailormade/getallupdates");
        },
        getRegions: function () {
            return $http.get("/umbraco/api/axumtailormade/getregions");
        },
        getCountries: function () {
            return $http.get("/umbraco/api/axumtailormade/getcountries");
        },
        getAreas: function () {
            return $http.get("/umbraco/api/axumtailormade/getareas");
        },
        getCities: function () {
            return $http.get("/umbraco/api/axumtailormade/getcities");
        },
        getCategories: function () {
            return $http.get("/umbraco/api/axumtailormade/getcategories");
        },
        getPackages: function () {
            return $http.get("/umbraco/api/axumtailormade/getpackages");
        },
        getHotels: function () {
            return $http.get("/umbraco/api/axumtailormade/gethotels");
        },
        getActivities: function () {
            return $http.get("/umbraco/api/axumtailormade/getactivities");
        }
    };
})

解决方案

Rather than returning a string from your methods, could you instead return a simple object containing the result and message for client?

public class ResponseMessage
{
    public bool Result { get; set; }
    public string Message { get; set; }
}

Then when executing GetAllUpdates() you would check result of GetCountries(), GetAreas() and GetCities() and append any error messages.

public ResponseMessage GetAllUpdates()
{
    ResponseMessage response;

    response = GetCountries();
    if (!response)
    {
        return response;
    }

    response = GetAreas();
    if (!response)
    {
        return response;
    }

    response = GetCities();
    if (!response)
    {
        return response;
    }

    response.Result = true;
    response.Message = "Successful";

    return response;
}

public ResponseMessage GetCountries()
{
    var response = new ResponseMessage();

    try
    {
        // Your main code here, call services etc

        response.Result = true;
        response.Message = "GetCountries successful";
    }
    catch (TimeoutException ex)
    {
        Log.Error("Web Service Timeout", ex);
        response.Result = false;
        response.Message = "Failed to contact web services.";
    }
    catch (Exception ex)
    {
        Log.Error("Exception", ex);
        response.Result = false;
        response.Message = "An error has occurred.";
    }

    return response;
}

It is a little more effort and code but will also give you more control over the flow and what's returned to client. You could also optimise it quite a lot I'm sure, I just stubbed out a general approach for you...

这篇关于在方法的WebAPI在异常返回错误信息给最终用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆