0

Using an ActionResult: if everything goes well return new EmptyResult if something goes wrong throw an exception. However as not all code paths return a value I need to add some sort of return in at the bottom of the function. Preferably an http request...404 maybe.

What im trying to do is Run this function from a console app ad download the PLU records to a CSV file. This all works fine, but throws an error with the 'return'....any ideas welcome

public ActionResult GetPLUInfo()
    {
        try
        {
            //CSV FILE of PLUs
            IEnumerable<PLURecord> listOfPLUs = _pluService.GetAll();

            using (StreamWriter outfile = new StreamWriter(@"C:\Users\Martin\Desktop\chocListWRITE.csv", true)) //true:  append text to a file with StreamWriter. The file is not erased, but just reopened and new text is added to the end. 
            {
                foreach (PLURecord _plu in listOfPLUs)
                {
                    string line = _plu.Serialize();
                    outfile.WriteLine(line);
                    Console.WriteLine(line);
                }

            }

            HttpContext.ApplicationInstance.CompleteRequest();



          return new EmptyResult();
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetPLUInfo.");
                Console.WriteLine(ex.Message);
            }

            //RETURN: How can i say here to return a http request error,
            //Using the ActionResult
        }
John
  • 3,965
  • 21
  • 77
  • 163
  • possible duplicate of [Returning 404 Error ASP.NET MVC 3](http://stackoverflow.com/questions/5635114/returning-404-error-asp-net-mvc-3) – hutchonoid Jan 30 '14 at 12:29
  • thanks for the answers guys iv decided to go with the personalized msg...return new HttpStatusCodeResult(404, "Error in GetPLUInfo"); – John Jan 30 '14 at 13:11

3 Answers3

0

You can set the Response.StatusCode to a valid http error like:

Response.StatusCode = 500;

Then you can let your error handling in the web.config handle what to do, redirect to a custom action of your own or just return the page.

jonezy
  • 1,903
  • 13
  • 21
0

Source So

As per this post you can return like this

return new HttpStatusCodeResult((int)HttpStatusCode.BadRequest);
Community
  • 1
  • 1
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73
0

You can just try this

catch (Exception)
        {
            throw;
        }
andy_b
  • 31
  • 2