Sunday, 15 July 2012

asp.net - How can I handle exceptions in WebAPI 2. methods? -



asp.net - How can I handle exceptions in WebAPI 2. methods? -

in webapi 2.1 application processing inserts this:

[route("post")] public async task<ihttpactionresult> post([frombody]city city) { if (!modelstate.isvalid) { homecoming badrequest(modelstate); } seek { db.exams.add(city); await db.savechangesasync(user, datetime.utcnow); } grab (exception ex) { var e = ex; homecoming badrequest("error: city not created"); } homecoming ok(city); }

i utilize similar updates , deletes. think should more meaningfull exceptions not sure start how handle these. looked @ elmah said deals unhandled exceptions. mean should not catching exceptions this?

can give me pointers if have okay , should logging exceptions , how?

what doing not "bad", it's bit verbose , won't scale if have many try/catch blocks on code. when exception raised, decide so, returning bad request response fine if it's bad request. there many things can return, depending on went wrong. have handle when exceptions thrown on code, maintaining logic scattered on code can become problem.

it's improve utilise asp.net web api's exception handling framework. example, take @ these articles:

http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling

the thought centralise logic in global exception handler , utilize place in code have worry this. rest of code throwing exceptions , coming through exception handler/filter/etc., depending on decide.

for example, have created own exception types (e.g. customexceptiona, customexceptionb, etc.) , when throw exception of type know how handle in 1 place , perform bit of logic. if want alter way handle particular exception type, there's 1 place have create alter , rest of code unaffected.

the sec article link above includes global exception logger log such exceptions.

asp.net asp.net-mvc asp.net-web-api

No comments:

Post a Comment