Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用.net核心Web Api中的自定义错误拦截器全局处理错误是否很好_.net_Asp.net Core_Webapi_Custom Errors - Fatal编程技术网

使用.net核心Web Api中的自定义错误拦截器全局处理错误是否很好

使用.net核心Web Api中的自定义错误拦截器全局处理错误是否很好,.net,asp.net-core,webapi,custom-errors,.net,Asp.net Core,Webapi,Custom Errors,我想问你们,这种全局处理错误的方法好吗?或者更好的方法是使用try-catch块来处理错误。 以下是处理错误的两种不同方法: 全局处理程序 public class ErrorDetails : Exception { public int StatusCode { get; } public override string Message { get; } public override string ToString() { return Js

我想问你们,这种全局处理错误的方法好吗?或者更好的方法是使用try-catch块来处理错误。 以下是处理错误的两种不同方法:

全局处理程序

public class ErrorDetails : Exception
{
    public int StatusCode { get; }
    public override string Message { get; }
    public override string ToString()
    {
        return JsonConvert.SerializeObject(new {Message});
    }

    public ErrorDetails(int statusCode, string message) 
    {
        Message = message;
        StatusCode = statusCode;
    }
}
public class GlobalErrorHandler
{
    private readonly RequestDelegate _next;
    public GlobalErrorHandler(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await _next(httpContext);
        }
        catch (ErrorDetails ex)
        {
            await HandleExceptionAsync(httpContext, ex);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(httpContext, ex);
        }
    }
    private Task HandleExceptionAsync(HttpContext context, ErrorDetails exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = exception.StatusCode;
        return context.Response.WriteAsync(exception.ToString());
    }
    private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return context.Response.WriteAsync(exception.ToString());
    }
}
然后在代码中抛出错误,或者还有第二种方法

public async Task<Response<User>> Create(User user)
    {
        try
        {
            var userFromDatabase = await _repository.Queryable().FirstOrDefaultAsync(x => x.Email == user.Email);
            if (userFromDatabase != null) return new Response<User>("Taki użytkownik już istnieje.");
            user.Password = new PasswordHasher<string?>().HashPassword(null, user.Password);
            await _repository.InsertAsync(user);
            return new Response<User>(user);
        }
        catch(Exception ex)
        {
            return new Response<User>($"Error: {ex.Message}");
        }
        
    }
public class Response<TEntity> where TEntity : class
{
    public readonly string Message;
    public readonly bool Success;
    public readonly TEntity Entity;
    public readonly List<TEntity> Entities;
    private Response(TEntity entity, List<TEntity> entities, string message, bool success)
    {
        Entity = entity;
        Entities = entities;
        Success = success;
        Message = message;
    }
    public Response(string message) : this(null, null, message, false) {}
    public Response(TEntity entity) : this(entity, null, null, true) {}
    public Response(List<TEntity> entities) : this(null, entities, null,true) {}
}
公共异步任务创建(用户)
{
尝试
{
var userFromDatabase=wait _repository.Queryable().FirstOrDefaultAsync(x=>x.Email==user.Email);
if(userFromDatabase!=null)返回新的响应(“Taki użytkownik jużistnieje”);
user.Password=new PasswordHasher().HashPassword(null,user.Password);
wait_repository.InsertAsync(用户);
返回新的响应(用户);
}
捕获(例外情况除外)
{
返回新响应($“错误:{ex.Message}”);
}
}
公共类响应,其中tenty:class
{
公共只读字符串消息;
公共只读文件的成功;
公共只读实体;
公共只读列表实体;
私有响应(TEntity实体、列表实体、字符串消息、bool成功)
{
实体=实体;
实体=实体;
成功=成功;
消息=消息;
}
公共响应(字符串消息):此(null,null,message,false){}
公共响应(TEntity实体):这个(实体,null,null,true){}
公共响应(列出实体):这个(null,entities,null,true){}
}
这种方法基于发送给控制器的响应obj,然后在控制器中基于我们发送给用户对象或消息的
Response.Success

我的问题是:全局错误处理可以吗?还是最好在每个服务中使用try-catch


提前感谢:)

在我看来,全局错误处理程序更有用。特别是当您有自己的自定义异常需要以特定方式处理时。它还将处理任何未处理的异常,并优雅地处理它