Web API将自定义异常返回给客户端 [英] Web API throw custom exception back to client

查看:83
本文介绍了Web API将自定义异常返回给客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在执行以下操作以将错误消息发送回客户端:

Currently, I'm doing the following to send error messages back to the client:

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
    ReasonPhrase = "No rights to access this resource",
};

throw new HttpResponseException(message);

但是,我想通过发送回自定义异常来进一步改善响应.所以我可以有这样的东西:

However, I would like to improve the response further by sending back custom exceptions. So I can have something like this:

public class MyAppException : Exception {}

public class NoRightsException : MyAppException {}
public class SaveException : MyAppException {}    
//etc...

我所有的例外都将放在单独的程序集中,服务器和客户端都将引用它们.

All my exceptions will be in a separate assembly that will be reference by both the server and the client.

如何最好地将这些异常返回给客户端,客户端将如何检查响应是我的自定义异常,另一个异常还是仅仅是一条短信?

How is the best to return these exceptions to the client and how will the client have to check whether the response is my custom exception, another exception or simply a text message?

推荐答案

要回答问题的第一部分,返回异常的正确方法是使用Request.CreateErrorResponse.此方法有许多重载,其中有一个将异常作为参数.就您而言,您可以...

To answer the first part of your question..the correct way to return exceptions is to use Request.CreateErrorResponse. This method has a number of overloads one of which takes the exception as a parameter. In your case you might do...

Request.CreateErrorResponse(HttpStatusCode.BadRequest, new NoRightsException());

更新:

尽管您尚未说明您的客户端方法是什么,但我将假设您使用的是HttpClient.如果是这种情况,您应该拨打与此电话类似的电话...

Although you haven't stated what your client method is I'm going to assume you are using HttpClient. If this is the case you should be making a call similiar to this...

var client = new HttpClient();

var task = client.PostAsync(url)
            .ContinueWith(response =>
            {
                response.Result.EnsureSuccessStatusCode();
            });

task.Wait();

在这种情况下,您将在响应类中找到文本或异常

in which case you will find the text or the exception in the response class

这篇关于Web API将自定义异常返回给客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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