在Web浏览器上显示自定义错误消息

时间:2017-12-08 03:36:18

标签: c# asp.net error-handling

我创建了一个ASP.NET Web API,它调用java Web服务器来检索数据。当Java Web服务器关闭时,我希望Web API显示错误消息:export class AppComponent { title = 'app'; router: string; constructor(private _router: Router){ this.router = _router.url; } } 为了实现在浏览器上显示的自定义错误消息,我应添加哪些代码?

以下是我的代码:

RestfulClient.cs

{"ErrorMessage:" Server is down}

AdditionController.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)
        {
            //What do i have to code here?
        }
        return null;
    }

}

有人请帮助我,非常感谢你。

1 个答案:

答案 0 :(得分:0)

如果您捕获类型Exception的异常,然后确定您调用的服务器已关闭,则情况并非如此。在您调用其他服务之前或在其他服务成功返回之后,您自己的代码中可能会出现问题。因此,您需要谨慎做出决定。

话虽如此,仍然很难说你何时可以放心地做出这样的决定:呼叫服务是否会返回正确的消息等。

无论如何,你可以做类似的事情:

try
{
    // ...
}
catch (System.Net.WebException ex)
{
    if (ex.Status == System.Net.WebExceptionStatus.ConnectFailure)
    {
        // To use these 2 commented out returns, you need to change 
        // your method's return type to Task<IHttpActionResult>
        // return Content(System.Net.HttpStatusCode.ServiceUnavailable, "Unavilable.");
        // return StatusCode(System.Net.HttpStatusCode.ServiceUnavailable);
        return "Unavailable"
    }
}
catch(Exception ex)
{
    // You could be here because something went wrong in your server,
    // or the server you called which was not caught by the catch above
    // because it was not WebException. Make sure to give it some 
    // thought.
    // You need to change 
    // your method's return type to Task<IHttpActionResult> or 
    // just return a string.
    return StatusCode(System.Net.HttpStatusCode.InternalServerError);
}