2

I implement user-defined exception in javascript code but it is not catching the exception.

I am providing my code :

function sendRequest(URL, Data, authorization, requestType,cuboidName) {
var Response = new $.Deferred();
var json;
if (requestType.toString() == "GET") {
    $.ajax({
        url: URL,
        type: "GET",
        dataType: "json",
        headers: {
        'Authorization': authorization,
        'Accept': 'application/json'
        },
        success: function (result) {
        Response.resolve(result);
        //console.log("Response : " + JSON.stringify(result) + "\n\n\n");

        },
        error: function(err){
            throw new Error("Error Code:\t"+err.status+"\nReason:\tCuboid Download failed for Cuboid:"+cuboidName);
        }
    });
}
return Response.promise();
}

I am calling the sendRequest function from the following code :

async loadDatatypeCuboid(dataCuboid)
{
    try
   {
    dataTypeCuboiId = "444";
    var res3 = new $.Deferred(); 
    Utils.sendRequest(this.baseUrl+"rest/v1/grid/"+dataTypeCuboiId+"?importTid=-1&view=LATEST&mode=0&baselineId=-1", null, Globals.authorization, "GET","Datatype").then(function (result) {
        res3.resolve(result);
        if (result.status == 500) {
        return;
        }
        else{

            } 
       });
        return res3.promise();
    }
    catch (error)
   {
        console.log(error);
    }
}

I am not able to catch the thrown error. The console is showing as :

Utils.js:26 Uncaught Error: Error Code: 500 Reason: Cuboid Download failed for Cuboid:Datatype

can anyone suggest How to Handle Exceptions in JavaScript Promise? Thanks in Advance

Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
Jaydeep Bobade
  • 1,005
  • 2
  • 16
  • 25
  • Possible duplicate of [How do I handle errors with promises?](https://stackoverflow.com/questions/21800010/how-do-i-handle-errors-with-promises) - the issue is that you are not using the `.catch` method on the returned promise. `try-catch` won't work because Promises _hide_ the exception under the `.catch` call. If you don't have one then the error will be "silenced" and never thrown outside the Promise. – Sergiu Paraschiv Nov 12 '18 at 11:02

0 Answers0