简体   繁体   中英

Should I check WebOperationContext.Current is null?

On my WCF Service I'm using the WebOperationContext to change the Outgoing Response and add a new header there.

Something like:

WebOperationContext context = WebOperationContext.Current;

context.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest;
context.OutgoingResponse.Headers.Add("MyHeader", "MyText");

If context is NULL something really bad happened at that point but since Resharper is complaining about the possibility of context being NULL I would like to ask you guys if the best approach would be to check if context is not NULL and just fail to fulfill the request (maybe I won't even know it failed) or just let the service crash (an option that I don't really like but at least I will know the service failed)?

You could check whether it's null and still crash, only by manually throwing an exception with an explicit error message instead of dereferencing a null reference.

The former will be informative, while the NullReferenceException is rather unhelpful when it comes to debugging errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM