简体   繁体   中英

Best Way to display a user friendly error message for the users, when an DBupdateexception occurred

I have the following code inside my action method :

Try {
    repository.Save();
    DetailBox b = new DetailBox() { 
        Tag = repository.getTechnologyTagByIT360ID(resourceid) 
    };

    return PartialView("_detailBox", b);
}
catch (DbUpdateException e)
{
    ModelState.AddModelError(string.Empty, "Error occurred:" +
        e.InnerException.InnerException.Message);
}

Currently, if the DbUpdatException occurs it will show the following error to the user:

• Error occurred: Violation of UNIQUE KEY constraint 'IX_Technology_2'. Cannot insert duplicate key in object 'dbo.Technology'. The duplicate key value is (18605). The statement has been terminated.

Which is not very bad, but at the same time, it is not very user friendly. Now there are many reasons why the DbUpateException might occur, so I can not define my own message . So, which approach should I take? Should I, for example, write a service method that check if the duplicate key value (18605) already exists in the database just before the repository.Save(); ?

Is message "user friendly" or not depends on your application users domain.

What about error message delivery to the client, I usually approach that in this way:

in ASP.NET controller when something bad happens write:

Response.StatusCode = (int)HttpStatusCode.BadRequest;
..
return Json(errorDataObjectInstance);

which on client side in hypothetical ajax request will raise error event

$.ajax( {

    ...
     error: errorHandler //this one will be called.
});

And after, naturally, using some client UI framework (bootstrap for example) show to the user in some way that information.

Catching exceptions is something you do to deal with unexpected situations, typically when interacting with systems that are beyond your own control, like file systems, services and yes, databases.

But exceptions should be that - exceptional. That is, whenever you can anticipate them you should try to prevent them from being thrown. You should never use them for program flow control. So if a user can enter duplicate database entries, check first and return a decent message when the constraint is violated. It's part of normal validation of user input. Same as you don't allow an exception to occur when a string value is too long for a database field.

The final catch should still be there, but now it really becomes exceptional , that is, when the same value happens to get entered by a concurrent user in the tiny time lapse between the check and the commit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM