WebApi v2 ExceptionHandler not called

后端 未结 2 1804
情话喂你
情话喂你 2020-12-14 07:27

How comes that a custom ExceptionHandler is never called and instead a standard response (not the one I want) is returned?

Registered like this

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 08:17

    Turns out the default only handles outermost exceptions, not exceptions in repository classes. So below has to be overridden as well:

    public virtual bool ShouldHandle(ExceptionHandlerContext context)
    {
        return context.ExceptionContext.IsOutermostCatchBlock;
    }
    

    UPDATE 1

    WebAPI v2 does not use IsOutermostCatchBlock anymore. Anyway nothing changes in my implementation, since the new code in ShouldHandle still prevents my Error Handler. So I'm using this and my Error Handler gets called once. I catch errors in Controllers and Repositories this way.

    public virtual bool ShouldHandle(ExceptionHandlerContext context)
    {
        return true;
    }
    

    UPDATE 2

    Since this question got so much attention, please be aware that the current solution is the one linked by @JustAMartin in the comments below.

提交回复
热议问题