[英].Net Core Handle exceptions that returned from web api
I'm using.Net 5.0 as backend and.Net 5.0 for client-side.我使用.Net 5.0 作为后端,使用.Net 5.0 作为客户端。
I want to know how to handle exceptions that returned from web api in Client Side and show them to client.我想知道如何在客户端处理从 web api 返回的异常并将它们显示给客户端。
The api result on exception is like: api 异常结果如下:
{
"Version": "1.0",
"StatusCode": 500,
"ErrorMessage": "User not found!"
}
How to handle this type of exception globally in the client side (using.Net Core MVC)?如何在客户端全局处理此类异常(使用.Net Core MVC)?
According to your description, I suggest you could use try catch on the server-side to capture the exception and return as a json response.根据您的描述,我建议您可以在服务器端使用 try catch 来捕获异常并作为 json 响应返回。
In the client side, you could use deserlize the response and create a new view named Error to show the response message.在客户端,您可以使用反序列化响应并创建一个名为 Error 的新视图来显示响应消息。
More details, you could refer to below codes:更多细节,您可以参考以下代码:
Error Class:错误 Class:
public class APIError
{
public string Version { get; set; }
public string StatusCode { get; set; }
public string ErrorMessage { get; set; }
}
API: API:
[HttpGet]
public IActionResult Get()
{
try
{
throw new Exception("UserNotFound");
}
catch (Exception e)
{
return Ok(new APIError { Version="1.0", ErrorMessage=e.Message, StatusCode="500" });
}
}
Application:应用:
var request = new HttpRequestMessage(HttpMethod.Get,
"https://localhost:44371/weatherforecast");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseStream = await response.Content.ReadAsStringAsync();
APIError re = JsonSerializer.Deserialize<APIError>(responseStream, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
});
if (re.StatusCode == "500")
{
return View("Error", new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, Version = re.Version, StatusCode = re.StatusCode, ErrorMessage = re.ErrorMessage });
}
}
else
{
// Hanlde if request failed issue
}
Notice: I created a new Error view, you could create it by yourself or modify the default error view.注意:我新建了一个错误视图,你可以自己创建或者修改默认的错误视图。
Error Viewmodel:错误视图模型:
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public string Version { get; set; }
public string StatusCode { get; set; }
public string ErrorMessage { get; set; }
}
Error view:错误视图:
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>@Model.StatusCode</h3>
<p>
@Model.ErrorMessage
</p>
Result:结果:
If you don't want to use exceptions in the backend, you could just send the http status code to the client.如果您不想在后端使用异常,您可以将 http 状态码发送给客户端。 Here is an example of reaching out to an external api via service and returning that status to the backend controller.
这是通过服务联系外部 api 并将该状态返回到后端 controller 的示例。 You would then just GET this result via client side.
然后,您只需通过客户端获取此结果。 You could also just send over the full http response to the client, instead of solely the HttpStatusCode if needed.
如果需要,您也可以只向客户端发送完整的 http 响应,而不是仅发送 HttpStatusCode。
A little more elaboration here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client在这里更详细一点: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client
//Backend Service..
private const string baseUrl = "https://api/somecrazyapi/";
public async Task<HttpStatusCode> GetUserStatusAsync(string userId)
{
var httpResponse = await client.GetAsync(baseUrl + "userId");
return httpResponse.StatusCode;
}
//Backend Controller
[ApiController]
[Route("[controller]")]
public class UserController
{
private readonly IUserService service;
public UserController(IUserService service)
{
this.service = service;
}
......
[HttpGet("{userId}")]
public HttpStatusCode GetUserStatus(string userId)
{
return service.GetUserStatusAsync(userId).Result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.