简体   繁体   English

如何处理 try/catch 块中的空变量?

[英]How to handle empty variables in a try/catch block?

So I have button that sends a POST request along with two variables, an outbox ID called oid , and an email .所以我有一个按钮,它发送一个POST请求以及两个变量,一个名为oid的发件箱 ID 和一个email The controller takes in the variables and performs a method call, the end goal would be to send a JSON response back depending on whether it fails or succeeds. controller 接收变量并执行方法调用,最终目标是根据失败或成功返回JSON响应。

I have the following written for the controller:我为 controller 编写了以下内容:

public ActionResult ResendEmail(int oid, string email = null)
{
    try
    {
        Outbox.ResendEmail(oid, email);
        return Json(new { success = true, message = "Email has been queued to be resent", status = (int)HttpStatusCode.OK });
    }
    catch (Exception)
    {
        return Json(new { success = false, message = "An error occurred when attempting to resend the email", status = (int)HttpStatusCode.InternalServerError });
    }
}

Problem here, is that 1. If the oid and/or email is empty, the method call for Outbox.ResendEmail(oid, email) will still be called and a success json response will be returned.这里的问题是 1. 如果oid和/或email为空,仍然会调用Outbox.ResendEmail(oid, email)的方法调用,并返回成功的 json 响应。 I'm also unsure if this is a proper way to use try/catch.我也不确定这是否是使用 try/catch 的正确方法。

Feels like I should re-write how i'm handling this.感觉我应该重写我是如何处理这个的。 Maybe an if statement to check for an existing oid and email followed by a try/catch?也许是一个 if 语句来检查现有的oidemail ,然后是 try/catch?

The try/catch is useful for handling exceptions . try/catch 对于处理异常很有用。 If Outbox.ResendEmail() throws an exception, then the try/catch will do its thing.如果Outbox.ResendEmail()抛出一个异常,那么 try/catch 会做它的事情。

However, if Outbox.ResendEmail() will not throw an exception when given an incorrect oid or an incorrect, empty, or null email , then you need something else, such as an if-statement.但是,如果Outbox.ResendEmail()在给定不正确的oid或不正确、空或 null email时不会抛出异常,那么您需要其他东西,例如 if 语句。

In addition, it probably is not appropriate to return a 500 error due to invalid parameters.此外,由于参数无效,可能不适合返回 500 错误。 It's not really a server error if the user passes a null email address.如果用户传递了 null email 地址,这并不是真正的服务器错误。

I would recommend something like the following:我会推荐如下内容:

public ActionResult ResendEmail(int oid, string email = null)
{
    // If you have a way to validate the oid, then use that instead of just checking for 0:
    if (oid == 0)
    {
        return // one of the 400 level responses
    }

    // Do you have a way to validate the email address?
    // If so, probably do that here, depending on how Outbox.ResendEmail() behaves
    if (string.IsNullOrWhiteSpace(email))
    {
        return // one of the 400 level responses
    }

    try
    {
        Outbox.ResendEmail(oid, email);
        return Json(new { success = true, message = "Email has been queued to be resent", status = (int)HttpStatusCode.OK });
    }
    catch (Exception)
    {
        return Json(new { success = false, message = "An error occurred when attempting to resend the email", status = (int)HttpStatusCode.InternalServerError });
    }
}

Try Catch always work with exception. Try Catch 总是在异常情况下工作。 As per the below statement in your question, it seems that Outbox.ResendEmail does not throw exception根据您问题中的以下陈述,似乎Outbox.ResendEmail不会引发异常

If the oid and/or email is empty, the method call for Outbox.ResendEmail(oid, email) will still be called and a success json response will be returned.如果 oid 和/或 email 为空,则仍将调用 Outbox.ResendEmail(oid, email) 的方法调用,并返回成功的 json 响应。 I'm also unsure if this is a proper way to use try/catch我也不确定这是否是使用 try/catch 的正确方法

instead of exception, it may be returning response with status false or error or not 200. That why, it is not going to catch and returning json response with success = false.而不是异常,它可能返回状态为 false 或错误或不是 200 的响应。这就是为什么,它不会捕获并返回 json 响应,成功 = false。

you can do like this你可以这样做

public ActionResult ResendEmail(int oid, string email = null)
{
   if ( oid <=0 || string.IsNullOrWhiteSpace(email) || validation of email if any)
    { 
      return response; // with statuscode among 400 and proper message in response 
                      //that where is the problem in request.
    } 

    try
    {
        var response= Outbox.ResendEmail(oid, email);
        if (response.StatusCode == 200) // condition for check that response is false or success 
        {
          return Json(new { success = true, message = "Email has been queued to be resent", status = (int)HttpStatusCode.OK });
        }

        return Json(new { success = false, message = "An error occurred when attempting to resend the email", status = (int)HttpStatusCode.InternalServerError });


    }
    catch (Exception)
    {
        return Json(new { success = false, message = "An error occurred when attempting to resend the email", status = (int)HttpStatusCode.InternalServerError });
    }
}

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

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