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

问题描述 投票:0回答:1

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

这其中包括我的表格:

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 并且没有任何内容传递回我的形式。

c# .net sql-server asp.net-apicontroller
1个回答
0
投票

我认为因为抛出异常而不是在 try/catch 块内,或者接收 CreateHttpResponseException 的 catch 块正在吸收它并且不提供响应对象。

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

我的表单没有返回任何内容

最终的结果是什么?从您发布的表单代码来看,它应该弹出带有成功消息的消息框,或者弹出带有失败消息的消息框。到底发生了什么?

第二次编辑

以下更多信息,请在您的表单代码中使用它...

try
{
    HttpResponseMessage response = KorisniciService.PostResponse(k);

    if (response.IsSuccessStatusCode)
    {
        MessageBox.Show(Messages.add_usr_succ);
        DialogResult = DialogResult.OK;
        Close();
    }
}
catch(HttpResponseException ex)
{
    string message = ex.ReasonPhrase;

    if (string.IsNullOrEmpty(Messages.ResourceManager.GetString(ex.ReasonPhrase)))
        message = Messages.ResourceManager.GetString(ex.ReasonPhrase);


    MessageBox.Show("Error code: " + ex.StatusCode + " Message: " + message);
}
© www.soinside.com 2019 - 2024. All rights reserved.