问题描述
我有一个ASP.NET Core 1.0 Web API应用程序,试图弄清楚如果控制器调用的函数出错,则如何将异常消息传递给客户端.
I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors out.
我尝试了很多事情,但是没有实现IActionResult
.
I have tried so many things, but nothing implements IActionResult
.
我不明白为什么这不是人们所需要的普通东西.如果真的没有解决办法,有人可以告诉我为什么吗?
I don't understand why this isn't a common thing that people need. If there truthfully is no solution can someone tell me why?
我确实使用HttpResponseException(HttpResponseMessage)
看到了一些文档,但是为了使用它,我必须安装compat垫片.在Core 1.0中,有没有一种新的方式可以做到这些?
I do see some documentation out there using HttpResponseException(HttpResponseMessage)
, but in order to use this, I have to install the compat shim. Is there a new way of doing these things in Core 1.0?
这是我一直在尝试使用匀场片的方法,但是它不起作用:
Here is something I have been trying with the shim but it isn't working:
// 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
时,我在客户端上查找,但找不到内容中正在发送任何内容的消息.
When the HttpResponseException
is thrown, I look on the client and can't find the message I am sending anything in the content.
推荐答案
这是一个简单的错误DTO类
Here is an simple error DTO class
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);
}
});
});
这篇关于错误处理(将ex.Message发送给客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!