returns 与 InternalServerError(ex) 相同的全局异常处理程序

Global Exception handler that returns same as InternalServerError(ex)

我有几个控制器。每一种都有几种方法。每个方法都有一个包含相同内容的 try/catch 块:

    catch (Exception ex)
    {
        return InternalServerError(ex);
    }

这个return是我需要的异常信息json。我很确定它只是序列化为 json.

的异常对象

我想做的是拥有一个全局异常处理程序,这样我就可以摆脱所有的 try/catch 块并清理我的控制器。

这是要点。我看到的示例不 return 我需要的 return。这就是为什么我认为这不是重复的。

这是我的代码,供那些想看的人使用。

public class GlobalExceptionHandler : IExceptionHandler

{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
        //HttpResponseMessage response =
        //                            new HttpResponseMessage(HttpStatusCode.InternalServerError);
        //response.Content = new StringContent(JsonConvert.SerializeObject(con);
        //response.RequestMessage = Request;
        //return Task.FromResult(response);
    }
}

找到合适的article后,结果很简单:

public class GlobalExceptionHandler : IExceptionHandler

{
    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
    {
        return Task.FromResult(context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, context.Exception.Message));
    }
}