title: How to handle stored procedure raiserror in mvc controller
body: <p>I am developing an asp.net mvc site using database first approach.</p>
  
  <p>I have a simple stored procedure like this:</p>
  
  <pre><code>ALTER PROCEDURE [dbo].[ins_item]
      -- Add the parameters for the stored procedure here
      -- item supplied must be in the reference db
      @item varchar(50)
  AS
  BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;
  
      -- Insert statements for procedure here
      select item 
      from reference.dbo.all_items 
      where item_name = @item
  
      if @@ROWCOUNT !=1
      begin
          raiserror('supplied item is not found in the master item list.', 11,1)
              return -1
      end
      --Now you know the item is in the reference, insert and handle any errors
  END
  </code></pre>
  
  <p>When I execute this in SQL Server Management Studio with an item that doesn't exist in the reference db, I get this error as expected:</p>
  
  <blockquote>
    <p>Msg 50000, Level 11, State 1, Procedure ins_item, Line xx<br>
    supplied item is not found in the master item list.</p>
  </blockquote>
  
  <p>In my asp.net mvc application, I imported this stored procedure into my model and in one of my controllers I have this code:</p>
  
  <pre><code>public ActionResult Create(item item)
  {
      if (ModelState.IsValid)
      {
          try
          {
              var insertresult =  db.ins_item(item.item1);
  
              db.SaveChanges();
          }
          catch (Exception e)
          {
              ViewBag.error = e;
          }
  
          return RedirectToAction("Index");
      }
  
      return View(item);
  }
  </code></pre>
  
  <p><code>db.ins_item</code> looks like this inside my model's database context that inherits from <a href="https://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext(v=vs.113).aspx" rel="nofollow">DbContext</a> class:</p>
  
  <pre><code>public virtual ObjectResult&lt;string&gt; ins_item(string item)
  {
      var itemParameter = item!= null ?
                  new ObjectParameter("item", item) :
                  new ObjectParameter("item", typeof(string));
  
      return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction&lt;string&gt;("ins_item", itemParameter);
  }
  </code></pre>
  
  <p>The issue is I don't get an exception when this action gets executed. How do I catch the raiserror that the stored procedure returns in the above controller action?</p>