asp.net mvc - TempData is empty when set in a catch block and we rethrow -
i using custom errors (web.config
) send unhandled exceptions errorcontroller
.
in main controller throw exception, catch in catch
block , set tempdata
have user-friendly message. throw
sent errorcontroller
.
when check tempdata
here, empty (as session
be, wouldn't it?).
i sure not meant empty, , right way of sending data between controllers... not working! mistaken in understanding?
homecontroller
:
catch (exception ex) { tempdata["msgforuser"] = "useful message show"; // logging... throw; }
errorcontroller
:
public actionresult displayerror(int id) { viewbag.msgforuser = tempdata["msgforuser"]; return view(); }
web.config
:
<system.web> <customerrors mode="on" defaultredirect="~/errorpage/displayerror"> <error redirect="~/error/displayerror/403" statuscode="403" /> <error redirect="~/error/displayerror/404" statuscode="404" /> <error redirect="~/error/displayerror/500" statuscode="500" /> </customerrors>
i found session being destroyed upon doing throw
in top-level catch
block, because request error controller. did find returning redirecttoaction()
preserved it.
so, created own exception type:
public class myapplicationexception : exception { /// <summary> /// message can shown user i.e. not technical /// </summary> public string messageforuser { get; set; } public myapplicationexception() { } public myapplicationexception(string message, string messageforuser="") : base(message) { messageforuser = messageforuser; } public myapplicationexception(string message, exception inner, string messageforuser = "") : base(message, inner) { messageforuser = messageforuser; } }
then when encounter problem expecting , end sending user generic error page, use so:
if (mylist.count > 14) { throw new myapplicationexception("more 14 records received: " + mylist.count.tostring(), "there maximum limit of 14 records can processed @ time. please call discuss requirement process in greater quantities."); }
and upon catching pick out message user, log error, , return redirecttoaction()
go error page without losing tempdata
.
catch (myapplicationexception myappex) { // if there user-friendly message store displayerror show if (string.isnullorempty(myappex.messageforuser) == false) { tempdata["msgforuser"] = myappex.messageforuser; } // logging elmah or custom logger util.logerror(myappex, "myfunc() threw exception", args); // // cannot throw here because lose session & tempdata. have manual redirect. // return redirecttoaction("displayerror", "errorpage", new { id = 500 }); }
and in view, , display if exists:
<p> error occurred. please check & try again later. </p> @if (string.isnullorempty(viewbag.msgforuser) == false) { <p class="more-info">details: @viewbag.msgforuser</p> }
Comments
Post a Comment