问题描述
我有一个 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)
的文档,但为了使用它,我必须安装兼容垫片.在 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!