Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle expected SQL exception?

The following action is scaffold-ed by Visual studio. However, it will raise an exception if the to be deleted record has been referred by another table. I want to show a nice error message when the record has been referred. What's the good ways to do it?

  1. Test if the record is already referred before deletion? (However, as the database schema changes, there may be more references added later)
  2. Wrap the code in a try/catch block. (Does it work on the async/await statement)?
  3. ...

    // POST: /Venue/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(int id)
    {
        Venue venue = await db.Venues.FindAsync(id);
        db.Venues.Remove(venue);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    
like image 523
ca9163d9 Avatar asked Mar 12 '14 07:03

ca9163d9


1 Answers

Use the HandleException action filter. you can specify what type to handle (SqlException).

like image 57
tulde23 Avatar answered Oct 31 '22 20:10

tulde23