jeudi 19 décembre 2019

Is it good practice to use try catch only for a part of the code

When I submit the form, I need to validate the input data from an HTML form field, which comes from the user who submitted the data. So inside the Page_Load event, I added this.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            AntiForgery.Validate();
        }
        try
        {
            lblMessage.Visible = false;
            if (!Page.IsPostBack)
            {
                ViewState["UserDetails"] = null;
            }
        }
        catch (Exception ex)
        {
            Logger.LogErrorEvent(ex);
            OutputError(ex);
        }
    }

In above code you can see I have added a try-catch code excluding if (IsPostBack){AntiForgery.Validate();}. Is this good practice?

This is why I did it: AntiForgery.Validate(); throws an exception if anti CSRF check fails. When I add if (IsPostBack){AntiForgery.Validate();} inside try-catch block it throws an exception, but after the exception has been thrown, the application executes this button click code as well. I need to avoid it.

    protected void btnSaveUser_Click(object sender, ImageClickEventArgs e)
    {
        // Some code
    } 

So I added if (IsPostBack){AntiForgery.Validate();} code outside the try-catch and working as expected. But I need to know is this good practice?

Aucun commentaire:

Enregistrer un commentaire