Handling Errors In MVC

Unknown | 9:20 PM |

@{var dataFilePath = "~/dataFile.txt";
 
 var fileContents = "";
 var physicalPath = Server.MapPath(dataFilePath);
 var userMessage = "Hello world, the time is " + DateTime.Now;
 var userErrMsg = "";
 var errMsg = "";
 if(IsPost)
 {
 // When the user clicks the "Open File" button and posts
 // the page, try to open the created file for reading.
 try {
    // This code fails because of faulty path to the file.
    fileContents = File.ReadAllText(@"K:\batafile.txt");
    // This code works. To eliminate error on page,
    // comment the above line of code and uncomment this one.
    fileContents = File.ReadAllText(physicalPath);
 }
 catch (FileNotFoundException ex)
  {
     // You can use the exception object for debugging, logging, etc.errMsg = ex.Message;
    // Create a friendly error message for users.
    userErrMsg = "A file could not be opened, please contact "+ "your system administrator.";
    }
    catch (DirectoryNotFoundException ex)
    {
    // Similar to previous exception.
    errMsg = ex.Message;
    userErrMsg = "A directory was not found, please contact "+ "your system administrator.";
    }
 }
 else
 {
     // The first time the page is requested, create the text file.
     File.WriteAllText(physicalPath, userMessage);
 }
 }

 <!DOCTYPE html>
 <html lang="en">
 <head><meta charset="utf-8" />
 <title>Try-Catch Statements</title>
 </head><body>
 <form method="post" action="" >
 <input type="submit" name="Submit" value="Open File"/>
 </form>
 <p>@fileContents</p>
 <p>@userErrMsg</p>
 </body>
 </html>

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....