【问题标题】:Core layer exception error my program is crashing核心层异常错误我的程序正在崩溃
【发布时间】:2020-10-05 21:04:51
【问题描述】:

我的业务层

public IResult Register(UserRegisterDto userRegisterDto, string role)
        {
            try
            {
               
                ValidationTool.Validate(new RegisterDtoValidator(), userRegisterDto);

               ....
            }
            catch (Exception e)
            {

                throw;
                
            }
        }

我的异常中间件

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;
            
        }

【问题讨论】:

标签: c# .net-core asp.net-core-webapi


【解决方案1】:

据我所知,缺少一部分。您在哪里将 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
}

然后在 Configure 方法中将其连接到您的 Startup.cs 文件中:

app.UseMiddleware<ErrorHandlingMiddleware>();

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 2018-02-16
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多