返回任务的JSON错误消息 方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了返回任务的JSON错误消息 方法相关的知识,希望对你有一定的参考价值。

我创建了一个ASP.NET Web API,它将调用java Web服务并在JSON中显示一些结果。当java Web服务未运行时,我收到错误消息:

{“Message”:“发生错误。”,“ExceptionMessage”:“方法或操作未实现。”,“ExceptionType”:“System.NotImplementedException”,“StackTrace”:“at ApiClientJavaWebService.Models.RestfulClient。 C: Users attsuap1 Desktop Server Project ApiClientJavaWebService ApiClientJavaWebService Models RestfulClient.cs中的InternalServerError(异常异常):位于C:的ApiClientJavaWebService.Models.RestfulClient.d__3.MoveNext()中的第43行 r n Users attsuap1 Desktop Server Project ApiClientJavaWebService ApiClientJavaWebService Models RestfulClient.cs:line 36 r n ---从抛出异常的上一个位置开始的堆栈跟踪结束--- r n在System.Runtime .CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) r n在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) r n在System.Runtime.CompilerServices.TaskAwaiter 1.GetResult() r n at C: Users attsuap1 Des中的ApiClientJavaWebService.Controllers.AdditionController.d__1.MoveNext() ktop Server Project ApiClientJavaWebService ApiClientJavaWebService Controllers AdditionController.cs:第20行 r n ---从抛出异常的上一个位置开始的堆栈跟踪结束--- r n在System.Runtime.CompilerServices.TaskAwaiter .ThrowForNonSuccess(任务任务) r n在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) r n在System.Threading.Tasks.TaskHelpersExtensions.d__3`1.MoveNext() r n-- - 从抛出异常的先前位置开始的堆栈跟踪结束---在System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) r n处于System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)的 r n ) r n在System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() r n ---从抛出异常的上一个位置的堆栈跟踪结束--- r n在System.Runtime System.Runtime.CompilerServices.TaskAwaiter.Hand上的.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) r n System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() r n中的leNonSuccessAndDebuggerNotification(任务任务) r n n ---从抛出异常的上一个位置开始的堆栈跟踪结束--- r n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) r n在System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) r n ()“}

如何更改此设置以使错误消息显示为{"The server is not running."}

这是我的代码:

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);
    }
}

有人请帮帮我。非常感谢你提前。

答案

我认为,您无法在要提取数据的服务器中管理抛出异常消息。那么,你为什么不过滤异常;

        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
            }
        }
另一答案

我已经实现了我想要的。我意识到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 catch部分)

        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"}

以上是关于返回任务的JSON错误消息 方法的主要内容,如果未能解决你的问题,请参考以下文章

异步任务片段背景数据

JavaScript 可扩展的代码,并根据从服务器返回的错误甚至是静态方式,自动调整自定义消息.... JSON

错误代码:错误域 = NSCocoaErrorDomain 代码 = 3840“JSON 文本没有以数组或对象和允许未设置片段的选项开头。”

以 JSON 形式返回验证错误消息 - Laravel 6

如何在 asp.net web api 中返回 json 错误消息?

AFNetworking/Overcoat/Promisekit - 在错误消息中获取返回 json