c# - Handling WCF Rest Service exceptions only in one place -
i'm developing wcf rest service i'm going host on iis.
now i'm implementing service contract, , see i'm repeating same code on of methods when i'm trying handle exceptions.
this 1 of service contract method:
public void deletemessage(string message_id) { int messageid; outgoingwebresponsecontext ctx = weboperationcontext.current.outgoingresponse; if ((message_id == null) || (!int32.tryparse(message_id, out messageid)) || (messageid < 1)) { ctx.statuscode = system.net.httpstatuscode.badrequest; ctx.statusdescription = "message_id parameter not valid"; throw new argumentexception("deletemessage: message_id not valid", "message_id"); } try { using (var context = new adnlinecontext()) { message message = new message() { messageid = messageid }; context.entry(message).state = entitystate.deleted; context.savechanges(); ctx.statuscode = system.net.httpstatuscode.ok; } } catch (exception ex) { ctx.statuscode = system.net.httpstatuscode.internalservererror; ctx.statusdescription = ex.message; ctx.suppressentitybody = true; } }
on of methods throw argumentexception
or exception
, , manage them return http status code
.
is there way catch exceptions globally?
ms-recommended approach appears follow faultexception pattern. idea implement ierrorhandler interface. this answer explains how set in wcf configuration.
having seen implementation of pattern in old-style wcf service can tell makes sense complex enterprise-level scenarios. simple cases i'd stick throwing exceptions manually.
another alternative implement rest service web api. has nice exception handling strategy out of box , that's microsoft recommends rest development in .net technology guide business applications.
Comments
Post a Comment