简体   繁体   English

如何处理从SQL抛出的错误消息到controller.cs

[英]How do I handle error message thrown from SQL to controller.cs

I want to check for duplicate username is exist or not. 我想检查是否存在重复的用户名。

In my AddNewUser stored procedure 在我的AddNewUser存储过程中

I have used following code 我使用了以下代码

DECALRE @error nvarchar(500)
IF EXISTS(SELECT EMAIL FROM [USERSTABLE] WHERE Email= @Email)  
set @error = 'User already exists with email address '+@Email
RAISERROR (@error,16,1);    

Now I want to catch this error message on UserNameController.cs 现在,我想在UserNameController.cs上捕获此错误消息

try
{
 using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (SqlCommand cmd = new SqlCommand("sp_CreateNewUser", connection))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

            //some parameters
            cmd.ExecuteScalar();
}

catch(Exception ex)
{throw ex;}

Now in ex I'm getting that error message. 现在在ex我收到该错误消息。 But how to show it on View? 但是如何在View上显示呢? (.cshtml)? (.cshtml)?

What about storing 'ex' in a ViewBag / TempData and then displaying it in View. 'ex'存储在ViewBag / TempData ,然后在View中显示该ViewBag / TempData

PS: Pardon me if I am wrong, I don't have much knowledge on MVC. PS:请原谅我,如果我做错了,我对MVC知识不多。

One of the possible solutions would be to enable custom errors in web.config: 一种可能的解决方案是在web.config中启用自定义错误:

<system.web>
    <customErrors mode="On" />
</system.web>

Once that is done, create a new view named Error.cshtml in Views/Shared: 完成后,在Views / Shared中创建一个名为Error.cshtml的新视图:

@model System.Web.Mvc.HandleErrorInfo

<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h2>
        Sorry, an error occurred while processing your request.
    </h2>
    <p>Controller Name: @Model.ControllerName</p>
    <p>Action Name : @Model.ActionName</p>
    <p>Message: @Model.Exception.Message</p>
</body>
</html>
</html>

Now you will see exception message in this custom view when exception is thrown. 现在,当引发异常时,您将在此自定义视图中看到异常消息。 No need to catch it manually. 无需手动捕获。

On the View you need to create control to show the message about error - usually it will be clean or unvisible. View您需要创建控件以显示有关错误的消息-通常它将是干净的或不可见的。 If you got an error - put your message abot error in this control and make it visible. 如果遇到错误,请在此控件中添加错误信息,使其可见。

Change your code here 在这里更改代码

catch(Exception ex)
{/*there must be code to show message*/}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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