[英]How can I throw an exception in an ASP.NET Core WebAPI controller that returns an object?
In Framework WebAPI 2, I have a controller that looks like this: 在Framework WebAPI 2中,我有一个如下所示的控制器:
[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return await _service.DoSomethingAsync(license).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
throw new HttpResponseException(HttpStatusCode.InternalServerError, msg);
}
}
Sure enough, I get back a 500 error with the message. 果然,我收到消息的500错误。
How can I do something similar in ASP.NET Core Web API? 如何在ASP.NET Core Web API中执行类似的操作?
HttpRequestException
doesn't seem to exist. HttpRequestException
似乎不存在。 I would prefer to continue returning the object instead of HttpRequestMessage
. 我宁愿继续返回对象而不是HttpRequestMessage
。
What about something like this. 这样的事情呢。 Create a middleware where you will expose certain exception messages: 创建一个中间件,您将在其中公开某些异常消息:
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
context.Response.ContentType = "text/plain";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
if (ex is ApplicationException)
{
await context.Response.WriteAsync(ex.Message);
}
}
}
}
Use it in your app: 在您的应用中使用它:
app.UseMiddleware<ExceptionMiddleware>();
app.UseMvc();
And then in your action throw the exception: 然后在你的行动中抛出异常:
[Route("create-license/{licenseKey}")]
public async Task<LicenseDetails> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return await _service.DoSomethingAsync(license).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
throw new ApplicationException(msg);
}
}
A better approach is to return an IActionResult
. 更好的方法是返回IActionResult
。 That way you dont have to throw an exception around. 这样你就不必抛出异常了。 Like this: 像这样:
[Route("create-license/{licenseKey}")]
public async Task<IActionResult> CreateLicenseAsync(string licenseKey, CreateLicenseRequest license)
{
try
{
// ... controller-y stuff
return Ok(await _service.DoSomethingAsync(license).ConfigureAwait(false));
}
catch (Exception e)
{
_logger.Error(e);
const string msg = "Unable to PUT license creation request";
return StatusCode((int)HttpStatusCode.InternalServerError, msg)
}
}
It's better not to catch all exceptions in every action. 最好不要在每个动作中捕获所有异常。 Just catch exceptions you need to react specifically and catch (and wrap to HttpResponse) all the rest in Middleware . 只需捕获需要特别反应的异常并捕获(并包装到HttpResponse) 中间件中的所有其他内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.