如何解决核心层异常错误,我的程序崩溃了
我的业务层
public IResult Register(UserRegisterDto userRegisterDto,string role)
{
try
{
ValidationTool.Validate(new RegisterDtovalidator(),userRegisterDto);
....
}
catch (Exception e)
{
throw;
}
}
我的ExceptionMiddleware
private Task HandleExceptionAsync(HttpContext httpContext,Exception e)
{
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
string message = "Internal Server Error";
int statusCodes = httpContext.Response.StatusCode;
if (e.GetType() == typeof(ValidationException))
{
message = e.Message;
statusCodes = (int)HttpStatusCode.BadRequest;
}
return httpContext.Response.WriteAsync(new ErrorDetails
{
StatusCode = statusCodes,Message = message
}.ToString());
}
我的Api控制器
public IActionResult Registeractor(UserRegisterDto userRegisterDto)
{
var result = _authService.Register(userRegisterDto,Role.default_actor.ToString());
if (!result.Success)
{
return BadRequest(result.Message);
}
return Ok(result);
}
我的问题当我在业务层遇到一些错误时,我的程序崩溃了。当出现一些错误时,中间件就会出错。我想编程不崩溃直接来自我的中间件
{
"Message": "Internal Server Error","StatusCode": 500
}
因为我的中间件正在运行。
**我想这全都是关于扔
catch (Exception e)
{
throw;
}
解决方法
据我所知,缺少一部分。您在哪里将HandleExceptionAsync
任务作为中间件连接到您的项目?
您可能需要这样的东西:
/// <summary>
/// Middleware used to catch all exceptions and log them as errors and return a uniform API response for all errors.
/// </summary>
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly bool _isDevelopmentEnvrionment;
public ErrorHandlingMiddleware(RequestDelegate next,IWebHostEnvironment env)
{
_next = next;
_isDevelopmentEnvrionment = env.IsDevelopment();
}
/// <summary>
/// Method used to pipe any request through the error handling middleware and surrounding it with try-catch
/// </summary>
/// <param name="httpContext">HttpContext needs to be passed</param>
/// <returns></returns>
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext,ex);
}
}
// Your HandleExceptionAsync method here
}
,然后使用Startup.cs
方法将其连接到您的Configure
文件中:
app.UseMiddleware<ErrorHandlingMiddleware>();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。