前言
此方法由百度所得,找不到原文链接了
步骤
1.创建异常捕获类
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System.Threading.Tasks; namespace NoteServer.Core { /// <summary> /// 自定义webapi异常处理 /// </summary> public class SMExceptionFilter : IExceptionFilter { /// <summary> /// 发送异常时执行的代码 /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { var res = new ResResult(); res.Code = StatusCodes.Status500InternalServerError; res.Msg = "接口开小差了"; if (context != null && context.Exception != null && !context.Exception.Message.IsEmpty()) { res.Msg += "," + context.Exception.Message; } string errRet = res.ToJson(); if (context.ExceptionHandled == false) { context.Result = new ContentResult { Content = errRet, StatusCode = StatusCodes.Status200OK, ContentType = "application/json" }; } context.ExceptionHandled = true; } /// <summary> /// 异步发送异常时执行的代码 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task OnExceptionAsync(ExceptionContext context) { OnException(context); return Task.CompletedTask; } } }
2.在StartUp.cs中注册
services.AddControllers(option => { option.Filters.Add(new Core.SMExceptionFilter()); });
测试执行
int page; 不传递值,导致发出异常