Built something you're proud of? Tell the story. A quick G2 review of App Engine or Build Agent helps other developers see what's possible on ServiceNow. Share your experience.

How to print the log for new sn_ws_err.ServiceError(); in scripted rest API?

Ganeshm1
Tera Guru

Hi All,

Hope you are doing well!

 

I have configured few scripted rest API and used below method for error logging. When I tried to print the logs in the syslog table, non of the methods are printing these values in the log table. Please let me know if you have any idea on this to print the log. 


var err = new sn_ws_err.ServiceError();
err.setStatus('status');
err.setMessage('message');
err.setDetail('detail');

gs.info(err)
gs.info(JSON.stringify(err));
gs.info(err.toString());

 

 

Results: 

x_ej_imac_soluti_0: [object ServiceError]
x_ej_imac_soluti_0: {}
x_ej_imac_soluti_0: [object ServiceError]


ServiceNow doc says we are good to use this method but logging from this method looks like a challenge. 

https://developer.servicenow.com/dev.do#!/learn/learning-plans/xanadu/servicenow_application_develop...

Please let me know your thoughts on this. Thank you!

 

Best Regards,
Ganesh

2 REPLIES 2

Naveen20
ServiceNow Employee

This helper function approach is the cleanest — it keeps your code DRY and ensures every error is logged consistently:

function createAndLogError(statusCode, msg, detailMsg) {
    gs.error('REST API Error - Status: ' + statusCode 
             + ' | Message: ' + msg 
             + ' | Detail: ' + detailMsg);

    var err = new sn_ws_err.ServiceError();
    err.setStatus(statusCode);
    err.setMessage(msg);
    err.setDetail(detailMsg);
    return err;
}

// Usage
response.setError(createAndLogError(404, 'Record not found', 'No CI found with sys_id: ' + sysId));

One function call handles both logging and error creation, so you never accidentally forget to log an error or end up with mismatched values between your log and your response.

Tanushree Maiti
Kilo Patron

 

 

Option 1: Within the code , you can write it 

var errorReported= new sn_ws_err.ServiceError();  //this API used to set the custom error messages
        errorReported.setStatus(this.status);
        errorReported.setMessage(responseObject.body.message);
        errorReported.setDetail(responseObject.body.detail);
        return errorReported;

 

Option 2: you can create a function with parameter and within the code->after getting response -> call the function

 

LogError: function(status,detail, message) {
var errorReported = new sn_ws_err.ServiceError();
errorReported.setStatus(status);
errorReported.setDetail(detail);
errorReported.setMessage(message);
return errorReported;
},
 
Please mark this response as Helpful & Accept it as solution if it assisted you with your question.
Regards
Tanushree Maiti
ServiceNow Technical Architect
Linkedin: