异常处理时catch块中的System.Web.Http.HttpResponseException

时间:2018-12-02 00:09:03

标签: c# .net sql-server api asp.net-apicontroller

我故意违反数据库中的唯一约束,并尝试处理异常。

这是我的形式:

HttpResponseMessage response = KorisniciService.PostResponse(k);
                if (response.IsSuccessStatusCode)
                {
                    MessageBox.Show(Messages.add_usr_succ);
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    string message = response.ReasonPhrase;
                    if (string.IsNullOrEmpty(Messages.ResourceManager.GetString(response.ReasonPhrase)))
                        message = Messages.ResourceManager.GetString(response.ReasonPhrase);


                    MessageBox.Show("Error code: " + response.StatusCode + " Message: " + message);
                }

我的控制器:

public IHttpActionResult PostKorisnici(Korisnici obj)
        {
            if (!ModelState.IsValid)
                return BadRequest();
            try
            {
                obj.KorisnikId = Convert.ToInt32(dm.esp_Korisnici_Insert(obj.Ime, obj.Prezime, obj.Email, obj.Telefon, obj.KorisnickoIme, obj.LozinkaSalt, obj.LozinkaHash, obj.Status, obj.Adresa, obj.GradId).FirstOrDefault());
            }
            catch (EntityException ex)
            {
                throw CreateHttpResponseException(Util.ExceptionHandler.HandleException(ex), HttpStatusCode.Conflict);
            }


            foreach (var item in obj.Uloge)
            {
                    dm.esp_KorisniciUloge_Insert(obj.KorisnikId, item.UlogaId);
            }
            return CreatedAtRoute("DefaultApi", new { id = obj.KorisnikId }, obj);
        }

HttpResponseException生成函数:

private HttpResponseException CreateHttpResponseException(string reason, HttpStatusCode code)
        {


            HttpResponseMessage msg = new HttpResponseMessage()
            {
                StatusCode = code,
                ReasonPhrase = reason,
                Content = new StringContent(reason)
            };
            return new HttpResponseException(Request.CreateResponse(msg));
        }

异常处理程序类:

public class ExceptionHandler
    {
        public static string HandleException(EntityException error)
        {

            SqlException ex = error.InnerException as SqlException;

                switch (ex.Number)
                {
                    case 2627:
                    {
                        return GetConstraintExceptionMessage(ex);
                    }
                    default:
                        return error.Message + "(" + error +")";
                }
        }
        /*Message "Violation of UNIQUE KEY constraint 'CS_KorisnickoIme'. Cannot insert duplicate key in object 'dbo.Korisnici'. The duplicate key value is (farish).\r\nThe statement has been terminated."    string*/

        private static string GetConstraintExceptionMessage(SqlException error)
        {
            string newMessage = error.Message;
            int startIndex = newMessage.IndexOf("'");
            int endIndex = newMessage.IndexOf("'", startIndex + 1);

            if (startIndex>0 && endIndex>0)
            {
                string constraintName = newMessage.Substring(startIndex + 1, endIndex - startIndex - 1);

                if (constraintName == "CS_KorisnickoIme")
                    newMessage = "username_con";
                else if (constraintName == "CS_Email")
                    newMessage = "email_con";


            }
             return newMessage;
        }

因此,当我发生错误时,而不是弹出窗口(在教学视频中可以正常显示),我在post方法的第一个catch块中得到了 System.Web.Http.HttpResponseException >,什么也没有传回我的表单。

1 个答案:

答案 0 :(得分:0)

我认为是因为引发了异常,而不是在try / catch块内,或者接收到CreateHttpResponseException的catch块正在吸收该异常,而不提供响应对象。

编辑 您可以发布KorisniciService.PostResponse的代码吗?

  

什么也没有传回我的表单

最终结果是什么?从您发布的表单代码中,它应该是带有成功消息的弹出消息框,还是带有失败消息的弹出消息框。实际发生了什么?

第二次编辑

进一步的信息,请在您的表单代码中使用它...

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.10'
    id("org.springframework.boot") version "2.1.0.RELEASE"
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    implementation group: "org.bytedeco.javacpp-presets", name: "tesseract", version: "4.0.0-rc2-1.4.3"
    implementation group: "org.bytedeco.javacpp-presets", name: "tesseract", version: "4.0.0-rc2-1.4.3", classifier: "windows-x86_64"
    implementation group: "org.bytedeco.javacpp-presets", name: "leptonica", version: "1.76.0-1.4.3", classifier: "windows-x86_64"
    implementation group: "org.springframework.boot", name: "spring-boot", version: "2.1.0.RELEASE"
    implementation group: "org.springframework.boot", name: "spring-boot-starter-web", version: "2.1.0.RELEASE"
    implementation group: "org.springframework", name: "spring-websocket", version: "5.1.2.RELEASE"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}