首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >错误处理(向客户端发送ex.Message )

错误处理(向客户端发送ex.Message )
EN

Stack Overflow用户
提问于 2016-06-24 21:15:29
回答 7查看 60.1K关注 0票数 42

我有一个ASP.NET Core1.0WebAPI应用程序,并试图弄清楚如果我的控制器正在调用的函数出错,如何将异常消息传递给客户端。

我尝试了很多方法,但都没有实现IActionResult

我不明白为什么这不是人们需要的普通东西。如果真的没有解决方案,谁能告诉我为什么?

我确实看到一些使用HttpResponseException(HttpResponseMessage)的文档,但是为了使用它,我必须安装compat shim。在Core1.0中有没有一种新的方式来做这些事情?

下面是我一直在尝试的填充程序,但它不起作用:

// GET: api/customers/{id}
[HttpGet("{id}", Name = "GetCustomer")]
public IActionResult GetById(int id)
{
    Customer c = _customersService.GetCustomerById(id);
    if (c == null)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent("Customer doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
            StatusCode = HttpStatusCode.NotFound

        };

        throw new HttpResponseException(response);

        //return NotFound();
    }
    return new ObjectResult(c);
}

当抛出HttpResponseException时,我查看客户端,但找不到要在内容中发送任何内容的消息。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2016-06-24 21:55:23

下面是一个简单的错误DTO类

public class ErrorDto
{
    public int Code {get;set;}
    public string Message { get; set; }

    // other fields

    public override string ToString()
    {
        return JsonConvert.SerializeObject(this);
    }
}

然后使用ExceptionHandler中间件:

            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    context.Response.StatusCode = 500; // or another Status accordingly to Exception Type
                    context.Response.ContentType = "application/json";

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        var ex = error.Error;

                        await context.Response.WriteAsync(new ErrorDto()
                        {
                            Code = <your custom code based on Exception Type>,
                            Message = ex.Message // or your custom message
                            // other custom data
                        }.ToString(), Encoding.UTF8);
                    }
                });
            });
票数 61
EN

Stack Overflow用户

发布于 2016-08-21 04:47:44

是的,可以将状态代码更改为您需要的任何代码:

在CustomExceptionFilterAttribute.cs文件中,按如下所示修改代码:

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        context.Result = new ContentResult
        {
            Content = $"Error: {exception.Message}",
            ContentType = "text/plain",
            // change to whatever status code you want to send out
            StatusCode = (int?)HttpStatusCode.BadRequest 
        };
    }
}

差不多就是这样。

如果您有自定义的异常,那么您也可以在从上下文中抓取抛出的异常时检查它们。接下来,您可以根据代码中发生的情况发送不同的HTTP状态代码。

希望这能有所帮助。

票数 9
EN

Stack Overflow用户

发布于 2016-06-24 21:44:59

您可以创建自定义异常过滤器,如下所示

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        context.Result = new JsonResult(exception.Message);
    }
}

然后将上述属性应用于您的控制器。

[Route("api/[controller]")]
[CustomExceptionFilter]
public class ValuesController : Controller
{
     // GET: api/values
    [HttpGet]
    public IEnumerable<string> Get()
    {
        throw new Exception("Suckers");
        return new string[] { "value1", "value2" };
    }
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38014379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档