开发者

How to handle Linq to Entity exceptions (errors)?

开发者 https://www.devze.com 2023-01-05 01:24 出处:网络
What is the best way to handle linq to entity exceptions? Can I use try and catch b开发者_StackOverflowlock or is there better way?We used a try block to shield us from Save errors.

What is the best way to handle linq to entity exceptions? Can I use try and catch b开发者_StackOverflowlock or is there better way?


We used a try block to shield us from Save errors.

try{
  using(Context context = new Context()){
     Entity x = context.Entities.First();
     x.ModifyMe = true;
     context.SaveChanges();
   }
 }catch(UpdateException e){
  //convert to friendly message
 }

If you want to catch a lower exception there is also a OptimisticConcurrencyException

We also took it a bit further and just wrapped our SaveChanges in an extension method that was called protected save changes.

public static class Extension{
  public static List<Error> ProtectedSaveChanges(this ObjectContext context){
      try{
        context.SaveChanges();

      }catch(UpdateException e ){
          //Convert to freindly and return
      }
  }

}

And believe it or not we decided to take it even further and have a special function that defined how to convert the exception method to a more user friendly error. If you want that one as well let me know and I can post.

As for an alternative way, i have seen people use exception shielding (EL), but i do not know if any built in Event Handlers for errors.

0

精彩评论

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

关注公众号