Returning JSON error message for Task<ihttpactionresult> method

时间:2017-12-18 06:19:38

标签: c# asp.net error-handling

I have created an ASP.NET Web API that will call a java web service and display some results in JSON. When the java web service is not running, i get the error message as:

{"Message":"An error has occurred.","ExceptionMessage":"The method or operation is not implemented.","ExceptionType":"System.NotImplementedException","StackTrace":" at ApiClientJavaWebService.Models.RestfulClient.InternalServerError(Exception exception) in C:\Users\attsuap1\Desktop\Server Project\ApiClientJavaWebService\ApiClientJavaWebService\Models\RestfulClient.cs:line 43\r\n at ApiClientJavaWebService.Models.RestfulClient.d__3.MoveNext() in C:\Users\attsuap1\Desktop\Server Project\ApiClientJavaWebService\ApiClientJavaWebService\Models\RestfulClient.cs:line 36\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()\r\n at ApiClientJavaWebService.Controllers.AdditionController.d__1.MoveNext() in C:\Users\attsuap1\Desktop\Server Project\ApiClientJavaWebService\ApiClientJavaWebService\Controllers\AdditionController.cs:line 20\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Threading.Tasks.TaskHelpersExtensions.d__3`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"}

How do i change this to get the error message to be shown as {"The server is not running."}?

Here are my codes:

AdditionClient.cs

public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {

        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }

        catch (Exception e)
        {

        }

        return null;
    }
}

AdditionController.cs

public class AdditionController : ApiController
{
    private RestfulClient restfulClient = new RestfulClient();
    public async Task<IHttpActionResult> Get(int firstNumber, int secondNumber)
    {
        var result = await restfulClient.addition(firstNumber, secondNumber);
        var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
        return Json(resultDTO);
    }
}

Someone please do help me. Thank you so much in advance.

2 个答案:

答案 0 :(得分:1)

I think, you can't the manage throwing exception messages in the server which you want to pull data. So, why don't you just filter the exception;

        try
        {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
        }

        catch (Exception e)
        {
            if (e.InnerException.Message == "The method or operation is not implemented")
            {
                //Do something
            }
        }

答案 1 :(得分:0)

我已经实现了我想要的。我意识到try catch方法应该在控制器类而不是AdditionClient.cs类中。

以下是我编辑过的课程:

<强> AdditionClient.cs

public class RestfulClient
{
    private static HttpClient client;
    private static string BASE_URL = "http://localhost:8080/";

    static RestfulClient()
    {
        client = new HttpClient();
        client.BaseAddress = new Uri(BASE_URL);
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<string> addition(int firstNumber, int secondNumber)
    {
            var endpoint = string.Format("addition/{0}/{1}", firstNumber, secondNumber);
            var response = await client.GetAsync(endpoint);
            return await response.Content.ReadAsStringAsync();
     } 
}

AdditionController.cs(专注于尝试捕捉部分)

        try
        {
            var result = await restfulClient.addition(firstNumber, secondNumber);
            var resultDTO = JsonConvert.DeserializeObject<Temp>(result);
            return Json(resultDTO);
        }

        catch (Exception e)
        {
            var result = @"Server is down";
            return Ok(new { ErrorMessage = result });
        }

当服务器未运行时,浏览器上显示的结果为{"ErrorMessage":"Server is down"}