c# - Sending overwriting response on HttpContext.Current is not a good idea? -
i have service people use odata in order filter data. sample string goes $orderby=[ssn]&$top=3. when string cannot parsed throws invalidcastexception , catch , tell user query cannot parsed.
here's problem. approach need try/catch on every controller action clutters code , don't how looks. imagine have 5 actions in controller , every single 1 of them wrapped same try/catch.
example
public ihttpactionresult home() { try { var users = db.getcollection("users") .asqueryable() .asfilteredobjects(request.requesturi.query); // line may cause exception return ok(users); } catch (invalidcastexception) { return badrequest(string.format("query ({0}) invalid.", request.requesturi.query)); } } what did
i removed try/catch controllers , moved inside asfilteredobjects , fiddled httpcontext.current return same response.
public static customjson asfilteredobjects(this iqueryable<bsondocument> documents, string query) { try { // removed because not relevent return json; } catch (invalidcastexception) { // simulate "return badrequest()" httpcontext.current.response.clear(); httpcontext.current.response.substatuscode = (int) httpstatuscode.badrequest; httpcontext.current.response.output.write("{\"message\":\"query (" + query + ") invalid.\"}"); httpcontext.current.response.contenttype = "application/json"; httpcontext.current.response.end(); return null; } } my question
for reason feels it's bad idea. wonder if there more elegant way of doing this?
in opinion, should use global exceptionhandler, new in web api 2.
this link tell exception handling in web api in general , this link should explain global exception handling in web api. allows throw exceptions on place , catch/handle them in 1 place.
previously, web api didn't have easy way handle errors globally. unhandled exceptions processed via exception filters, there number of cases exception filters couldn't handle. solution provide new user-replaceable service, iexceptionhandler, deal unhandled exceptions. provides access exception context containing relevant information point exception detected, particularly httprequestmessage, httprequestcontext, thrown exception , exception source.
by following examples in above links, in project i'm able throw sorts of exceptions , not worry try/catch @ point they're thrown (polluting code exception handling on place), global exception handler configured in 1 place , takes care of (almost) possible exceptions. , because every rule has "exception" (pun intended!), in case it's httpresponseexception type, not handled global exception handler.
Comments
Post a Comment