#代码片段/NetCore
NetCore Api中的错误处理
使用TryCatch处理异常
[HttpGet("/get1")]
public IActionResult Get1()
{
try
{
throw new Exception("The argument is null!");
}
catch (ArgumentNullException ex)
{
return NotFound(ex.Message);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
使用过滤器处理异常
创建过滤器:
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
var exception = context.Exception;
var result = new ObjectResult(new { error = exception.Message })
{
StatusCode = (int)HttpStatusCode.InternalServerError
};
context.Result = result;
}
}
全局注册过滤器:
builder.Services.AddControllers(opt =>
{
opt.Filters.Add<CustomExceptionFilter>();
});
抛出异常:
//TODO: 使用过滤器处理异常
[HttpGet("/get2")]
public IEnumerable<WeatherForecast> Get2()
{
throw new Exception("Something went wrong!");
}
过滤器结果:500 Error: response status is 500
{
"error": "Something went wrong!"
}
使用中间件处理异常
创建中间件:
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_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 exception)
{
var response = context.Response;
response.ContentType = "application/json";
var errorResponse = new
{
message = exception.Message,
innerException = exception.InnerException?.Message
};
return context.Response.WriteAsJsonAsync(errorResponse);
}
}
使用中间件:
app.UseMiddleware<ErrorHandlerMiddleware>();
抛出异常:
//TODO: 使用中间件处理异常
[HttpGet("/get3")]
public IActionResult Get3()
{
throw new Exception("Something went wrong!");
}
响应结果:200
{
"message": "Something went wrong!",
"innerException": null
}