UseExceptionHandler

app.UseExceptionHandler(configure =>
{
configure.Run(async context =>
{
var exHeader = context.Features.Get<IExceptionHandlerPathFeature>();
var ex = exHeader.Error;
if (ex != default)
{
await context.Response.WriteAsJsonAsync(new { code = 500, errPath = exHeader.Path, msg = $"服务器内部错误->{ex.Message}" });
} });
});

自定义中间件

app.UseMiddleware<ErrorHandlingMiddleware>();

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net; namespace TouristRouteWebApplaction.Middleware
{
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
if (ex is KeyNotFoundException) code = HttpStatusCode.NotFound;
//else if (ex is MyUnauthorizedException) code = HttpStatusCode.Unauthorized;
//else if (ex is MyException) code = HttpStatusCode.BadRequest;
var result = JsonConvert.SerializeObject(new { error = ex.Message });//JsonConvert.SerializeObject(errorObj, opts.Value.SerializerSettings)
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
}

最新文章

  1. PhotoShop简介
  2. xml配置文件
  3. 【mysql5.6】SQL基础
  4. VB.NET开发中遇到的一个小问题
  5. JAVA--线程wait()、lnotify()和notifyAll()方法
  6. Spring.Net控制翻转、依赖注入、面向切面编程
  7. JavaWEB开发国际化
  8. webStorm支持.wxml文件高亮显示
  9. tensorflow的简单操作
  10. js学习2
  11. iOS一些高效代码
  12. go test 测试用例那些事
  13. python爬虫高级功能
  14. Linux下TFTP服务的安装、配置和操作
  15. 转:深入理解css中position属性及z-index属性
  16. CSS文字过多显示省略号
  17. Linux FastDFS 分布式文件系统安装
  18. 安装vue后报错 bash: vue: command not found
  19. PyQt4工具栏
  20. Mysql命令行查看数据库大小(数据库版本为5.7以上)

热门文章

  1. 解决windows下使用vscode没有函数提示的问题
  2. Python中的__new__()方法
  3. python requests库从接口get数据报错Max retries exceeded with url解决方式记录
  4. 难搞的electron之安装
  5. rabbitmq监控与运维
  6. linux下启动jar包
  7. 在dockerfile使用定时任务遇见的坑
  8. 【Python】【算法】【排序】用Python实现排序的三种算法
  9. python下载站长素材免费简历模板(xpath)
  10. Hadoop环境的搭建