从catch块格式发送错误信息到客户端 [英] Sending formatted error message to client from catch block

查看:125
本文介绍了从catch块格式发送错误信息到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的code从过滤器(ActionFilterAttribute)发送错误信息到客户端。

i am using the following code to send out error message to client from a filter(ActionFilterAttribute).

catch (Exception)
 {
    var response = context.Request.CreateResponse(httpStatusCode.Unauthorized);
    response.Content = new StringContent("User with api key is not valid");
    context.Response = response;
 }

但问题是,它仅在纯文本发送。我想送它作为当前的格式化格式。像JSON或XML的形式。

But problem is that it sends out in plain text only. I wanted to send it as format of current formatter. Like in form of json or xml.

在这里,我知道这是因为我使用的StringContent()。但是我们怎么能写使用自定义的Error对象?
像,下面是不工作之一:

Here i know that this is because i am using StringContent(). But how can we write using custom Error object? like, the following is not working either:

response.Content = new Error({Message = "User with api key is not valid"});

我们如何写code这个?先谢谢了。

How do we write code for this? Thanks in advance.

推荐答案

雅,我发现写作的语法是否正确。我们可以这样写:

Ya, i found the correct syntax of writing. We can write like:

catch (Exception)
{
    var response = context.Request.CreateResponse(HttpStatusCode.NotFound, 
                        new Error { Message = "User with api key is not valid"});
    context.Response = response; 
}

这篇关于从catch块格式发送错误信息到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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