开发者

Asp.net MVC exception not being caught in try catch block

Could anyone tell me why a problem in the noun model would not be caught by this try catch?

I have tried this on two different controller methods now, and both times, even if the linq2sql doesn't allow the data to be saved, the code never jumps into the catch block.

I've watched the noun object in the middle of the trace, and the isvalid property is false, but the modelstate isvalid is true. Either way, the code never jumps into the catch block.

I'm pulling my hair out about this. I feel like it will be something really silly.

The code all works similar to nerd dinner.

NounRepository nounRepository = new NounRepository();
        Noun noun = new Noun();
        try
        {                
            UpdateModel(noun);
            nounRepository.Add(noun);
            nounRepository.save();
        }
        catch (Exception ex)
        {
            Mo开发者_开发技巧delState.AddRuleViolations(noun.GetRuleViolations());
            return View(noun);
        }
    return View(noun);

Update

I have just added this code, and now the rules are coming back to the front end fine, so it just seems that the try catch isn't catching!

UpdateModel(noun);

            if (!noun.IsValid)
            {

                var errors = noun.GetRuleViolations();
                ModelState.AddRuleViolations(noun.GetRuleViolations());
                return View(noun);

            }

            nounRepository.Add(noun);
            nounRepository.save();

I'd rather not have to add code in this manner though, as it seems like an unnecessary duplication.


You faced logical change in mvc - validation here do not throw exceptions. Indeed, you need to check it using if statement.

I doubt that exception is happening - you need to catch linq2sql exception anyway, code is correct. Also there is high a chance that inside 'save' or 'add' you have another catch - this is quite common mistake


Programming Rule #1: catch ain't broken (AKA: SELECT ain't broken).

If you're really in doubt, open up the Debug menu, choose "Exceptions", then tick the box for "Common Language Runtime Exceptions" under "Thrown." This will cause the debugger to break on all first-chance exceptions. If the debugger doesn't break during your update, then the exception is never getting thrown in the first place.

Don't forget to untick when you're done, as the behaviour gets pretty annoying under normal usage.

P.S. Never catch System.Exception. Catch the specific type(s) of exception(s) that you know might actually be thrown.


Are you doing something in another thread? That is often a cause exceptions not being caught.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜