ASP.NET核心Web Api中间件将自定义异常转换为基本异常
public class CustomException : Exception
{
public int HttpStatusCode { get; private set; }
public CustomException()
{
}
public CustomException(int httpStatusCode, string message):base(message)
{
HttpStatusCode = httpStatusCode;
}
}
public class ExceptionMiddleware
{
public readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch(CustomException ex)
{
await HandleExceptionAsync(httpContext, ex);
}
catch(Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
int statusCode = (int)HttpStatusCode.InternalServerError;
if (ex is CustomException)
{
CustomException se = ex as CustomException;
statusCode = se.HttpStatusCode;
}
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
return context.Response.WriteAsync(JsonConvert.SerializeObject(new InternalServerErrorResponse(ex.Message)));
}
}
throw new CustomException(StatusCodes.Status422UnprocessableEntity, "User is already registered!");
catch(Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
请指教。
您可以使用异常筛选器来处理异常并轻松地操作响应。
public class ExceptionFilter : IExceptionFilter
{
public ExceptionFilter(IHostingEnvironment env, ILogger<JsonExceptionFilter> logger)
{
_env = env;
_logger = logger;
}
public void OnException(ExceptionContext context)
{
var error = new ApiResponse();
var exceptionName = context.Exception.GetType().Name;
var message = context.Exception.Message;
if (_env.IsDevelopment())
{
error.Message = context.Exception.Message;
error.Detail = context.Exception.StackTrace;
}
else
{
//Prevent To Show Exception Messages On Production
error.Message = "Server Error Occured";
error.Detail = "Something wrong happened";
}
context.Result = new ObjectResult(error)
{
//Manipulate Status Code
StatusCode = 500
};
}
}
并注册到startup.cs
public void ConfigureServices(IServiceCollection services){
services.AddMvc(options =>
{
//Catch the exceptions
options.Filters.Add<ExceptionFilter>();
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
我的问题基本上是这样的--给定这里显示的代码,在试图启动对客户机的响应的管道中还有什么运行?我知道关于该异常的其他问题,但似乎在中间件之后运行的管道中有什么东西导致了异常--它不是由中间件引起的,我认为这是我的场景中的不同之处。 这是一个简单的ASP.NET Core3.0WebSocket echo服务器--没有信号、没有MVC、没有路由、没有静态页面支持等等。除了处理套接字之外,当中间件看到对
.NET核心和ASP.NET核心到底有什么区别?
中间件是 WebHook 的一种变种模式,不同的是它早于 WebHook 执行,你可以做一些有用的前置拦截,比如 token 校验、日志记录等等。 实现一个中间件可以参考一个例子: public class BasicAuthMiddleware implements WebHook { private static final int AUTH_LENGTH = 6; priv
与SqlAlchemy一起使用的异常。 基本异常类是 SQLAlchemyError . 由于DBAPI异常而引发的异常都是 DBAPIError . exception sqlalchemy.exc.AmbiguousForeignKeysError(*arg, **kw)¶ 在联接期间两个可选择项之间可以找到多个外键匹配时引发。 exception sqlalchemy.exc.Argumen