这是一个比较长的故事(我使用 jQuery 进行 API 调用)。
首先,我添加了如下的异常处理:
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context )
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = HttpStatusCode.InternalServerError;
var result = new BaseResponseDTO<string>()
{
ErrorCode = (int)HttpStatusCode.InternalServerError,
ErrorMessage = ex.Message,
Succeed = false,
};
var jsonResult = JsonConvert.SerializeObject(result);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(jsonResult);
}
}
然后注册它(在 app.UseMvc() 之前注册):
app.UseMiddleware(typeof(ErrorHandlingMiddleware));
app.UseMvc();
好的,接下来,请调用您的API。我通常会返回如下的DTO类:
public class BaseResponseDTO<T>
{
public bool Succeed { get; set; }
public string ErrorMessage { get; set; }
public T Result { get; set; }
public int? ErrorCode { get; set; }
}
现在来谈谈我的 Web API:有时会返回一个值,有时会抛出一个异常。
public BaseResponseDTO<string> TestApi()
{
var r = new Random();
var random = r.Next(0, 2);
if (random == 0)
throw new Exception("My Exception");
else
return new BaseResponseDTO<string>() { Succeed = true, Result = "Some result..." };
}
最终,通过jquery进行调用:
function callApi() {
$.ajax({
type: 'GET',
url: 'https://localhost:5001/Home/TestApi',
data: null,
dataType: 'json',
success: function (data) {
if (data.succeed) {
alert(data.result);
}
else {
alert(data.errorMessage);
}
},
error: function (error) {
debugger;
alert(error.responseJSON.ErrorMessage);
}
});
}
如果 Api 返回异常:
如果 Api 返回结果: