Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Generic" wrapper for MVC5 - Controllers?

I have a "generic" return value for my MVC5-Controllers which returns something like

{ Success: true, 
Item: {Id:1, Name:"Oink" },
Error:null,
Message:"Everything works fine"
}

I want to keep this structure even if an exception occures. So currently I use something like this in my controller:

try {
    var stuff=new Stuff();
    return ReturnSomeJson(stuff.GetStuff(),"Everything works fine", true, null);
} 
catch (Exception ex)
{
    return ReturnSomeJson(null, "That went wrong!", false, ex);
}

So this is the return method:

protected ReturnSomeJson (object item, string message, bool success, exception ex) {
    // more stuff
    return Json (this);
}

As this is quite a generic Exception handling I would like to avoid writing this try-catch over and over again.

I already fell about different Exception methods in MVC, but all these display an error message directly.

But I want to keep the "ActionResult" returnvalue when using a generic Error handling.

like image 915
Ole Albers Avatar asked Jun 24 '26 16:06

Ole Albers


1 Answers

I've studied the exception handling question quite a bit and my conclusion is that the best place to put your generic error handler is in global.asax.cs, Application_Error method. Also, disable ALL other error handling that you can find (including MVC's handling), because that can catch and swallow an exception without you knowing.

I chose Application_Error because it's the absolute final handler. If that doesn't catch a rogue exception (which wasn't swallowed), then nothing will. If you use, for example, MVCs error handling, then there are still some errors that can be missed - like an exception in Application_BeginRequest or a missing controller, or a DLL loading exception or whatever.

like image 172
Vilx- Avatar answered Jun 26 '26 08:06

Vilx-