Patrick
Patrick

Reputation: 2781

NLog use in MVC application

How can I use NLog to get detail information regarding a local error?

Until now I have this:

private static Logger logger = LogManager.GetCurrentClassLogger();

public ActionResult Index()
{
    try
    {
        var domain = db.Works.ToList();

        var model = Mapper.Map<IList<Work>, IList<WorkIndexViewModels>>(domain);

        return View(model);
    }
    catch (Exception e)
    {
        logger.Error("Error in Index: " + e);
    }
}

If I put the return after the catch, the model is out of scope.

If I put the return inside the try, I get "not all code path returns a value" from the Action.

So how can I solve this?

Upvotes: 0

Views: 388

Answers (1)

Jason W
Jason W

Reputation: 13209

Since you've already captured the error and you can't show the requested page, you could redirect within the catch to your error page:

    catch (Exception e)
    {
        logger.Error("Error in Index: " + e);
        return RedirectToAction("Index", "Error"); // Redirect to error controller or page
    }

Alternatively, and probably more appropriate, you could have your action raise a 500 error so that your error configuration within your web.config can properly handle redirection.

    catch (Exception e)
    {
        logger.Error("Error in Index: " + e);
        return new HttpStatusCodeResult(500); // Raise internal server error
    }

Upvotes: 2

Related Questions