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

為{幸葍}努か 提交于 2019-12-13 03:54:02

问题


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();?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/20150079/best-way-to-display-a-user-friendly-error-message-for-the-users-when-an-dbupdat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!