如何从WebAPI引发异常 [英] How to throw Exception from WebAPI

查看:65
本文介绍了如何从WebAPI引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有抛出异常的业务逻辑,我需要将其转移到我的api控制器并显示我的webapi无法读取的时间。我到处都放着托盘。在业务逻辑中

I have business logic which has throw exception, which I need to transfer to my api controller and show when my webapi fails to read. I have tray catch in all place. In Business Logic`

public static Models.User Login(Models.Login model)
        {
            try
            {
                using (var db = new Data.TPX5Entities())
                {
                    var query = (from a in db.User
                                 where a.UserID == model.UserName || a.UserCode == model.UserName || a.UserName == model.UserName
                                 select new Models.User
                                 {
                                     EMail = a.EMail,
                                     IsUsed = a.IsUsed,
                                     Memo = a.Memo,
                                     MobilePhone = a.MobilePhone,
                                     Password = a.Password,
                                     Telephone = a.Telephone,
                                     UserCode = a.UserCode,
                                     UserID = a.UserID,
                                     UserName = a.UserName
                                 }).ToList();
                    if (query == null || query.Count == 0)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserNotFound"));
                    }
                    else if (query.Count > 1)
                    {
                        throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_UserCodeRepeat"));
                    }
                    else
                    {
                        if (query[0].Password == model.Password)
                        {
                            return query[0];
                        }
                        else
                        {
                            throw new Exception(@LanguageHelper.GetSystemKeyValue(CultureHelper.GetCurrentCulture(), "/resource/Model/BLL_User_MSG_InCorrectPassword"));
                        }
                    }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

然后我使用Web API控制器再次尝试catch

then web api controller I use try catch again

 [HttpPost]
        public Models.User Login(Models.Login model)
        {
            Models.User mUser = null;
            try
            {
                mUser = BusinessLogic.User.Login(model);
                if (mUser == null)
                    throw new Exception("Object is null.");
            }
            catch(Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent(ex.Message, Encoding.UTF8), ReasonPhrase = "Login Exception" });
            }
            return mUser;
        }

然后我打电话给我的客户,我用try catch再次检查

and then I call in my client I use try catch to check again

private void btnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty( txtUser.Text))
            {
                TPX.Core.MessageBoxHelper.ShowError(Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Error_UserEmpty"));
                return;
            }
            try
            {               
                //登录系统
                string md5Password = TPX.Core.Security.MD5.GetMD5(txtPassword.Text);
                TPX.Models.Login mLogin = new TPX.Models.Login();
                mLogin.UserName = txtUser.Text.Trim();
                mLogin.Password = md5Password;
                //Retrieve User Information
                string itemJson = Newtonsoft.Json.JsonConvert.SerializeObject(mLogin);
                string userURL = GlobalParameters.Host + "api/User/Login";

                using (System.Net.WebClient webClient = new System.Net.WebClient())
                {
                    webClient.Headers["Content-Type"] = "application/json";
                    webClient.Encoding = Encoding.UTF8;
                    string sJson = webClient.UploadString(userURL, "POST", itemJson);

                    TPX.Models.User myDeserializedObj = (TPX.Models.User)Newtonsoft.Json.JsonConvert.DeserializeObject(sJson, typeof(TPX.Models.User));

                    ClientContext.Instance.UserID = myDeserializedObj.UserID;
                    ClientContext.Instance.UserCode = myDeserializedObj.UserCode;
                    ClientContext.Instance.UserName = myDeserializedObj.UserName;
                    ClientContext.Instance.Password = myDeserializedObj.Password;
                }
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (WebException ex)
            {
                TPX.Core.MessageBoxHelper.ShowException((Core.LanguageHelper.GetSystemKeyValue(GlobalParameters.Language, "/resource/Message/MS_FormLogin_Ex_LoginError")),ex);
            }

        }

当我以错误的凭据需求登录时引发错误。现在,我收到错误消息远程服务器返回错误:(500)内部服务器错误,而我想抛出我的业务逻辑抛出的确切错误。谢谢
`

When I login with wrong credential need to throw error. Now I am getting error "The remote Server return error:(500)Internal Server Error', Instead I want to throw exact error which my business logic throw. Thanks `

推荐答案

您的业务层和您的api是两个不同的东西。

your business layer and your api are two different things.

除非您不抛出api错误,否则

you don't throw errors from your api unless something really bad happened with your own code.

api总是返回有意义的http代码,这就是客户端如何知道发生了什么事情。

The api always returns meaningful http codes and that's how the clients know what's going on.

示例:

[HttpPost]
    public IHttpActionResult Login(Models.Login model)
    {
        var mUser = BusinessLogic.User.Login(model);
            if (mUser == null)
                return NotFound();

        return Ok(mUser);
    }

您现在正在返回对客户有意义的有意义的东西,并且您实际上是在帮助他们了解发生了什么。

you are now returning something meaningful which makes sense to a client and you are actually helping them understand what's going on.

返回数据的方式有多种,这只是其中一种。

There are multiple ways to return data, this is only one of them.

避免抛出错误,这在资源使用方面是昂贵的,并且用户数量越多,获得的后果就越糟。

Avoid throwing errors, it is expensive in terms of resources used and the more users you have the worse it will get.

您可以让您的业务层以字符串形式返回一条消息,然后由于API调用而返回该消息,另一个响应将向您显示操作方式。

You can have your business layer return a message in form of a string and then return that as a result of the API call and the other response shows you how.

这篇关于如何从WebAPI引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆