MVC SQL Error Exception encountered

I am encountering an issue with a SQL store procedure failure and trying to capture the exception being thrown. Although I am receiving the response in ajax using request.responseText, I am only interested in extracting the title from this responseText.

The Controller code snippet is shown below:

public ActionResult ReOrderSegment(string DocumentIDs, long DossierIDForReOrder) 
        {
            try
            {
                var TrimmedString = DocumentIDs.TrimEnd('#');

                var DocumentIDsWithInteger = Convert.ToInt64(DocumentIDs.Split('#').FirstOrDefault());

                long SelectedCompany = db.Documents.FirstOrDefault(x => x.ID == DocumentIDsWithInteger).CompanyID;

                var Message = db.PerformAutomatedSorting(SelectedCompany, DossierIDForReOrder, TrimmedString);

                return Json(Message, JsonRequestBehavior.AllowGet);

            }
            catch (SqlException ex)
            {
                Response.StatusCode = 500;
                Response.TrySkipIisCustomErrors = true;
                return Json(new { errorMessage = ex.Message }, JsonRequestBehavior.AllowGet);
            }

            return Json(0);
        }

and JS:

 $.ajax({
                    type: 'POST',
                    url: rootUrl("Dossier/ReOrderSegment"),
                    dataType: "json",
                    data: { DocumentIDs: DocumentIDs, DossierIDForReOrder: DossierIDForReOrder },
                    traditional: true,
                    success: function (rest)
                    {
                        alert(rest);

                    },
                    error: function (request, status, error)
                    {
                        //var all = JSON.parse(request.responseText);
                        alert(request.responseText);
                    }   
                });
            });

Attached are some images for reference.

In the alert message, I specifically want to display only "Please select only Air Product that are UnInvoiced".

Answer №1

Below is a snippet of code that can be implemented in your error handling block:

var newTitle = $(request.responseText).filter('title').text(); // alternatively, try find('title').text();

The variable newTitle above will display the title for you.

However, it is recommended to create a custom ErrorDetails class with properties such as a Message string, or a Messages List to store all validation messages and return them to the client. This can be achieved in your controller catch block like so:

ErrorDetails errorDetails = new ErrorDetails();
errorDetails.Message = "Please select only Air Product that are UnInvoiced";
return Json(errorDetails, JsonRequestBehavior.AllowGet);

When accessing the error details in jQuery code, you can do the following:

error: function(xhr, status, error) {
  var obj = $.parseJSON(xhr.responseText); //you can also directly use xhr.responseJSON instead of parsing
  alert(obj.Message);
  //utilize this obj to retrieve message or list of messages through a loop
}

Answer №2

Here is my approach to handling errors which you might find useful.

Within the base controller:

 protected virtual JsonResult HandleError(Exception exception, string customMessage = null, int statusCode = 500)
        {
            JsonNetResult result = new JsonNetResult();
            result.ContentType = "application/json";
            result.ContentEncoding = System.Text.Encoding.UTF8;
            result.Data = new JsonErrorModel(){ error = exception, message = customMessage };

            if (exception != null)
                Log.Error(customMessage, exception);
            else if (!string.IsNullOrWhiteSpace(customMessage))
                Log.Error(customMessage);

            int updatedStatus = statusCode;
            if (exception != null)
            {
                if (exception is ArgumentException || exception is ArgumentNullException || exception is CustomException)
                    updatedStatus = 400;
                var aggException = exception as CustomAggregateException;
                if (aggException != null)
                {
                    updatedStatus = 400;
                    customMessage = customMessage ?? string.Join("; ", aggException.Messages);
                }
            }

            if (Response != null)
            {
                Response.StatusCode = updatedStatus;
                Response.StatusDescription = customMessage ?? (exception == null ? "An error occurred" : exception.Message);
            }

            return result;
        }

Within the HomeController, extending the basecontroller:

 public JsonResult HandleTestCase(Model model)
        {
            try
            {
            }
            catch (Exception ex)
            {
                return HandleError(ex);
            }
        }

Considering refactoring this process to create a reusable exception-handling attribute or potentially managing error logic in the global.asax.cs application_error method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue of asynchronous behavior causing malfunctioning of the PayPal button

import { PayPalButton } from 'react-paypal-button-v2' <PayPalButton amount={total} onSuccess={tranSuccess} /> const tranSuccess = async(payment) => { c ...

Automated library that refreshes the webpage instantly upon any server modifications

Seeking a Javascript solution to automatically refresh a webpage when the server version is updated. Update: I am aware of the technical aspects involved and how to implement this feature. However, I am interested in finding an existing solution that I ca ...

What is the best method to retrieve the minimum and maximum values of a range slider in PHP and

I've successfully implemented a custom range slider using the code snippet below: HTML: <input type="text" class="salary" id="salary" name="salary" style="border:0; color:#f6931f; font-weight:bold;&qu ...

Node.js POST request only executes successfully on the second attempt

I am facing a peculiar issue where upon submitting a form, it redirects to the form action URL and then displays a blank page. However, upon reloading the page, the data is displayed. index.jade - http://172.18.0.60:3000/ form#command(action='runc ...

What is the best way to create an IF statement that will execute only when a specific variable, "id," is included in the URL

Is there a way to create an IF statement in PHP that will only be executed if a specific variable is encoded in the URL? I have a PHP page that retrieves and displays query results without reloading the page. When a user clicks on a particular query resul ...

Can one function be invoked from another function in Node.js?

As I delve into learning Node.js through the process of converting an existing Rails project, I find myself grappling with callbacks and the asynchronous nature of Node. It has been a challenging journey to wrap my head around these concepts. Initially, m ...

How can you nest a map within a map in JavaScript?

Here is the code snippet I am working with: _renderChannels() { return this.state.channelsData.map(channelData => { return this.state.channelsStreamData.map(channelStreamData => { return <Channel channelData={channelData} ch ...

Encountered an error while creating a PNG chart with node-export-server: Unexpected character '''

I am currently facing an issue when attempting to export a highchart graph using the node-export-server library; npm install highcharts-export-server -g Resource and Guide: https://github.com/highcharts/node-export-server#server-test Following the do ...

The Combobox event does not trigger properly on a change

My issue arises when trying to display the JDatePicker of jQuery UI in a different format upon an onchange event in a Combobox. The code I have does not work as expected when the second onchange event is triggered. Javascript Code $(document).ready(funct ...

Updating Model Property Value via AJAX Request

When I click on a table of data, I want to trigger a change. However, when I try to call the data in my initial model value (List), I encounter an error. POST https://localhost:7230/controller/List 404 This is My Controller [HttpGet] public async T ...

What is the best way to retrieve the current value of a header cell, including any nested headers?

My handsontable has headers that include checkboxes and select boxes. How can I access the headers to check the value of a select/checkbox inside the header cell? You can view an example in this JSFiddle (with nested headers - same as my project): http:/ ...

Sending HTML data from jQuery via Ajax to PHP and receiving a response

I'm trying to post data from a span when clicked, but nothing happens. The span contains the number '4'. I am not sure about the syntax for doing this. <span style="color:#B00" id="PidClick">4</span> This is how I am attempting ...

Is it possible to trigger the execution of two functions simultaneously by using onClick in JavaScript?

I currently possess: one = () => { //perform a task } two = () => { //execute an action } <div> <button onClick={/*this.one, this.two (it doesn't function)*/}>Go</button> </div> Is there a way to invoke two f ...

Trouble with passing AJAX calls from JavaScript object to PHP

I've encountered an issue while trying to extract information from a form and send it via AJAX to a PHP file for storing in a CSV file. Surprisingly, the PHP file is receiving the JavaScript object with empty fields even though they appear filled in t ...

Youtube does not trigger injection scripts in Safari extensions

During my work on a Safari extension, I encountered an issue with adding an End Script to Youtube pages. The script functions properly when the initial Youtube page loads, but if I click any links within the page, nothing happens unless I open them in a ne ...

Error occurred in Flask due to request names being dynamically generated using JavaScript

My current project involves creating an app that calculates transit projections based on input years and other variables. I've written a JavaScript script where users can add new types of vehicles, each generating a unique div with specific ids and na ...

javascript - convert a JSON string into an object without using quotation marks

Consider the following example: var mystring = `{ name: "hello", value: 1234 }` var jsonobj = JSON.parse(mystring) The code above will not output anything because the "name" and "value" keys are missing quotes. How can I parse this strin ...

Accessing User Input Data with JQuery

Can someone help me figure out how to store the input value from a Materialize select form in HTML using a variable in javascript/jquery? Here is the HTML code for the form: <div class="input-field col s12"> <select> <option va ...

Is there a variation in IE6 versions depending on the operating system used?

It's puzzling to me that customers are reporting bugs on W2K machines in IE6, yet when I test locally on a WinXP System, everything appears normal. Could it be possible that there are differences in JavaScript Execution between the two systems? I do ...

Secure your password with Vue JS encryption techniques

I am looking for a way to safely encrypt passwords on my Vue JS web application. While I already have a hash encrypter set up on the API, I am running into an issue where the password is displayed as plain text during the signin or signup call. Any recom ...