ASP.NET Core:如何将C#类异常状态码传递至TypeScript客户端
为自定义异常设置特定HTTP状态码的解决方案
步骤1:创建自定义异常类
替换系统自带的FormatException,定义专属异常类以便精准识别错误类型:
public class InvalidRepositoryUriException : Exception { public InvalidRepositoryUriException(string message) : base(message) { } }
步骤2:修改控制器抛出自定义异常
在控制器的检查逻辑中,抛出刚才定义的专属异常:
if (!repoUrlFormatMatch.Success) throw new InvalidRepositoryUriException($"The repositoryUri '{repositoryUri}' did not conform to the expected format for an Azure Devops Git repository.");
步骤3:全局捕获异常并返回指定状态码
可以通过全局异常过滤器或异常处理中间件实现,以下提供两种可选方案:
方案A:使用全局异常过滤器
- 实现异常过滤器类:
public class CustomExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { if (context.Exception is InvalidRepositoryUriException invalidRepoUriEx) { // 返回400 Bad Request(也可根据业务需求选用422 Unprocessable Entity) context.Result = new ObjectResult(new { Message = invalidRepoUriEx.Message }) { StatusCode = StatusCodes.Status400BadRequest }; context.ExceptionHandled = true; } // 其他未捕获异常默认返回500状态码 } }
- 在Program.cs(.NET 6+)中注册过滤器:
builder.Services.AddControllers(options => { options.Filters.Add<CustomExceptionFilter>(); });
方案B:使用异常处理中间件
在Program.cs中配置全局异常处理中间件:
app.UseExceptionHandler(errorApp => { errorApp.Run(async context => { var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>(); var exception = exceptionFeature?.Error; if (exception is InvalidRepositoryUriException invalidRepoUriEx) { context.Response.StatusCode = StatusCodes.Status400BadRequest; context.Response.ContentType = "application/json"; await context.Response.WriteAsJsonAsync(new { Message = invalidRepoUriEx.Message }); } else { // 通用服务器错误返回500状态码 context.Response.StatusCode = StatusCodes.Status500InternalServerError; context.Response.ContentType = "application/json"; await context.Response.WriteAsJsonAsync(new { Message = "An unexpected error occurred." }); } }); });
步骤4:客户端根据状态码处理提示
修改TypeScript代码,针对不同状态码展示对应提示信息:
const response = await fetch(`api/projectdecommissionrequest`, { body: JSON.stringify(postBody), headers: new Headers({ "Accept": "application/json", "Authorization": `Bearer ${token}`, "Content-Type": "application/json", }), method: "POST", }); if (response.ok) { console.log("Decommission request submitted successfully"); } else if (response.status === 400) { const error = await response.json(); alert(`Error: ${error.Message}`); } else if (response.status === 500) { alert("A server error occurred. Please try again later."); } else { alert(`Request failed with status code: ${response.status}`); }
内容的提问来源于stack exchange,提问作者Rutvik Lhase
相关产品推荐
相关产品推荐

