7

I am trying to return user friendly error message when a Mysql Exception is thrown in c#. I am currently returning the exception message but that message is not very user friendly. So I was wondering if any one of you had any trick that does not require any fancy regex parsing of the error messages received to display them to the user in a manner that would make sense to them.

I am trying to stay away from complex validation code prior to inserting/updating/deleting a record but that seems to be the only way ... unless you know better!

2
  • 2
    Every mysql error has an error code: dev.mysql.com/doc/refman/5.5/en/error-messages-server.html You can write your own error messages for those. Commented Nov 15, 2011 at 15:05
  • Hey Marc, that seems like a good idea but from which method in the exception object can I get this code ? I only seem to be getting the MySql.Data Exception and the message from the db without the error code Commented Nov 15, 2011 at 15:13

2 Answers 2

11

As Marc B pointed that every Mysql error has an error code, so you can catch a MySqlException using a try ... catch block like this:

try
{

}
catch (MySqlException ex)
{
    int errorcode = ex.Number;
}

So you can write a case statement to provide the error message for each error code, here are a list of server error codes and messages.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I figured my main problem was I was catching Exception and not the specific MySqlException so I did not have access to the Number attribute. Thanks a lot.
1

You could try catching the specific sql error message and display it

Try

Catch ex as SqlException
'''sql specific error message
''ie: 
response.write("oops! error message: " & ex.message)
Catch ex as Exception
'''any other runtime error messages
End Try

2 Comments

Hi Carlos, this is what I am currently doing but a duplicate key on insertion is not a message easily understandable by everyone I am trying to build on those error a user-friendly message like "the value entered is already present in the system"
Unfortunately there is no way of translating error messages into wording your average Joe will understand. What i've done in the past is use a resource file and put in one column the .Net exception message and then in the second column the enduser translation. Very tidious, but for that project i had a requirement that the error had to be easy to understand by the user. Exceptions are really designed for programmers to handle programmatically (translate intoa a userfriendly message, log the error, etc) to handle errors more gracefully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.