Handling errors using Parse.com Cloud Code and javascript API - parse-platform

What is the best way to handle errors using Parse.com Cloud Code. I'm able to use console.log and Firebug to see when Parse Cloud Code throws an error, but I need some help with how to notify the client that something went wrong. Some sample code from both sides would really be great -- Cloud Code and client side javascript code.

I preferred it this way -
On Cloud Code make one ErrorHandler.JS file -
exports.sendError = function(response, message, data) {
console.log("Message - " + message + " Data - " + JSON.stringify(data)); // To print LOG on Cloud Code
// Moreover you can use any of - "console.error/warn" - as mentioned - https://parse.com/docs/cloud_code_guide#logging
response.error({
status : false, // Indicates EXECUTION STATUS - I am using "successHandler" also & using STATUS as "true"
message : message, // Refers to Error Message
data : data || {} // Error Object or your customized Object
});
}
& client side you will have all data to print if you want or you can just show alert message to the Users.
More over it's preferred to check both SERVER side as well as CLIENT side LOG for DEVELOPING purpose because PARSE Cloud Code stores only last 100 messages in LOG.
& In order to implement proper LOGGING you must made some custom procedures with proper storage structure in terms of CLASS.

Parse has a section on Error Handling for Promises.
For instance when running a query in Cloud Code
query.find().then(function(result){ ... },
function(error){
response.error("Error occurred: " + error.message);
}
That will send error message down the client.

As an experiment I tried response.error with various strings/objects, below is what each returned (the commment shows the return value to the client).
Essentially, it always returns code 141, and you can only return a string. I was surprised that passing the proverbial err object from an exception returned {} my guess is this is for security reasons. What I do not understand is why you can't console.log(err) on the server as this has caused me a lot of confusion when trying to figure out what is going on. You basically always need to do err.message in your console.log statements to figure out what's really going on.
response.error("Some String of text") // --> {code: 141, message: "Some String of text"}
response.error( new Error("My Msg") ) // --> {code: 141, message: "{}"}
try {
var x = asdf.blah;
}catch(err) {
return response.error(err.message); // --> {code: 141, message: "asdf is not defined"}
}
response.error( err ); // --> {code: 141, message: "{}"}
response.error( Parse.Error(Parse.Error.VALIDATION_ERROR, "My Text") ); // --> {code: 141, message: "An error has occurred"}

Related

What defines the log type (Default, Alert, Error, Critical, etc) on logs out of a Cloud Run container instance?

I have an express server that is hosted on Cloud Run / Docker container.
This is the screen where we can view logs that come out of the deployed instance.
What defines the "type" of the log message: as in Alert, Critical, Error, Warning, Debug, Info, Notice and Default
If I log with console.error will it show up as an Error ?
What is the documentation on this subject?
UPDATE: Trying to log an error with the type Error
const logError = (msg: string | Error) => console.error(`[test:error] ${msg}`);
const testError = () : void => {
try {
throw new Error("TEST ERROR");
}
catch(err) {
const someError = new Error("HELLO ERROR");
console.log(someError);
console.error(someError);
logError(err);
logError("ERROR STRING MSG");
}
};
These were the results:
Not a single log with the type Error. Is this not supposed to be triggered by our code? When should it happen?
I'd like to filter logged messages from my catch blocks in some situations and I was hoping to filter for the Error log type. I guess I'll have to add the [error] string flag and filter for that.
How do people usually handle this?
Just install and use the Stackdriver node.js library if your goal is to send logs to Google Stackdriver (Operations Logging).

Unable to map the error getting from the application deployed using lambda function

I am having springboot application deployed using a lambda function. Please find the below sample.
Controller
#RequestMapping(method = RequestMethod.GET, value = "/bugnlow/findByRegionId/{regionId}", produces = "application/json")
public ResponseEntity<List<Bunglow>> findAllBunglowsByRegionId(#PathVariable int regionId, #RequestParam int page, #RequestParam int size) {
Page<Bunglow> bunglows = bunglowsService.findAllBunglowsByRegionId(regionId, page, size);
if (bunglows.getContent().size() == 0){
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(bunglows.getContent());
}
Service
if the "regionid" is invalid, I am throwing a runtime exception that contains message "region id is invalid".
throw new RuntimeException(Constant.INVALID_REGION_ID);
I am getting the below response when testing it locally by sending the invalid region id.
[1]{
"timestamp": 1519577956092,
"status": 500,
"error": "Internal Server Error",
"exception": "java.lang.RuntimeException",
"message": "Region Id is invalid",
"path": "/***/bugnlow/findByRegionId/343333"
}
I deployed above application AWS using lambda function. When I send the request from the AWS API gateway to the deployed application I am getting the below error with Amazon response headers.
[2] Request: /bugnlow/findByRegionId/342324?page=0&size=5 Status: 500 Latency: 166 ms Response Body
{ "message": "Internal server error" }
In the particular endpoint, integration responses have already configured for Error 500. But didn't use a template configuring the content-type as application/json.
I able to get the localized error by setting it in the controller class with
ResponseEntity<?>
But then the List Bunglow not display as the example response value in Swagger UI.
I need to get exact response[1] from the AWS console. How to do it.
Instead of error 500, how can I send the "Region id is invalid" with the Http status 400 (bad request).
It's a great help, if someone can help me on this.
Thanks
I able to resolve my problem by creating a class with
#ControllerAdvice
and handle the Exception using
#ExceptionHandler
Each point I need to validate and respond the error, I created an custom Exception "BunglowCustomExceptionResponse" and catch the exception in the Advice class "BunglowControllerAdvice". Then send the response with the exception message with bad request response as below.
#ControllerAdvice
public class BunglowControllerAdvice {
#ExceptionHandler
public ResponseEntity handleCustomBunglowException(Exception e){
logger.info("***Exception occurred :" + e.getLocalizedMessage());
return new ResponseEntity<BunglowCustomExceptionResponse>(new
BunglowCustomExceptionResponse(e.getLocalizedMessage()), HttpStatus.BAD_REQUEST);
}
}
Then, I able to get the expected response similar to below with bad request status code 400.
{"responseMessage": "error message"}
I don't know this is the best way but able to resolve my problem. Anyway, thanks a lot for your time who viewed this and tried to help me.

Kony service giving 1012 opstatus Request failed error and not giving response

I have a kony sample app where I am trying to do a build and the app has one web service in it for fetching categories of some product. I have the following code also that I wrote:
function GetCategories() {
var inputparam = {
"appID": "bbuy",
"serviceID": "GetCategories",
"catId": "cat00000",
"channel": "rc",
"httpheaders": {}
};
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
}
I am getting no response for this. Getting 1012 opstatus and the message is saying "Request failed" error.
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
In the above line, you have not given the port number in the MWservlet URL.(e.g. 8080) Give that and check.
Also, make sure all input params are being fed to the service and that they correspond to the exact naming convention followed in the service editor.
Visit :
Find the below link. i hope it gives you a solution
http://developer.kony.com/twiki/pub/Portal/Docs/API_Reference/Content/Network_APIs.htm#net.invo2
Check the mandatory and optional fields of Inputparam

Changing the "Upload failed" Message

I would like to change the "Upload failed" message to one returned from my server-side processing.
I can see the message I want in the onError callback but I'm not sure how to used that instead of the default message.
Thoughts, examples or further reading advice welcome (new here).
The implementation of what you're trying to do depends on whether you are using Fine Uploader Basic/Core or Regular/UI. This is because UI mode offers some extra goodies for displaying error messages and such.
A few properties/options that may benefit you:
Fine Uploader Basic/Core mode
text.defaultResponseError
Message sent to the onError callback if no specific information about the error can be determined. This is used if the server indicates failure in the response but does not include an “error” property in the response and the error code is 200 (XHR only)
var uploader = new qq.FineUploaderBasic({
/* ... */
text: {
defaultResponseError: "Oh noes! Upload fail."
}
});
The documentation on 'text'
Fine Uploader Regular/UI mode
failedUploadTextDisplay.mode option
Valid values are “default” (display the text defined in failUploadText next to each failed file), “none” (don’t display any text next to a failed file), and “custom” (display error response text from the server next to the failed file or Blob).
failedUploadTextDisplay.responseProperty option
The property from the server response containing the error text to display next to the failed file or Blob. This is ignored unless mode is “custom”.
var uploader = new qq.FineUploader({
/* ... */
text: {
defaultResponseError: "Oh noes! Upload fail."
},
failedUploadTextDisplay: {
mode: 'custom', // Display error responses from the server.
responseProperty: 'errorMsg' // Default is 'error', change this to match the
// property that contains the error message from
// your server
}
});
The documentation on failedUploadTextDisplay
For people who still use FineUploaded and above does not work, that is because the key is not changed to failUpload.
Usage for a custom message on UI end would be
text: {
failUpload: 'Your upload faile message goes here
},
More details can be found here - https://docs.fineuploader.com/branch/master/upgrading-to-4.html
If you want to display the server-side message, you can do it the below way:
failedUploadTextDisplay {
mode: 'custom',
responseProperty: 'server side error key goes here'
}
If you wish to completely remove it, i.e, not show the message below file if file upload has failed, use below
failedUploadTextDisplay {
mode: 'none'
}

log stack trace when HTTP request return error in Jmeter

I want to log all error message for failed HTTP request. I am going to run the thread group for 1B users and I don't want to use the View Result Tree because it logs everything and log file will bloat.
Currently I am using Beanshell Assertion as below.
if (Boolean.valueOf(vars.get("DEBUG"))) {
if (ResponseCode.equals("200") == false) {
log.info(SampleResult.getResponseMessage());
log.info("There was some problem");
}
}
But in this case it just prints the error message but I am interested to log the stack trace returned by the server.
I also used this method as mention in this thread
for (a: SampleResult.getAssertionResults()) {
if (a.isError() || a.isFailure()) {
log.error(Thread.currentThread().getName()+": "+SampleLabel+": Assertion failed for response: " + new String((byte[]) ResponseData));
}
}
But in this case I don't get an object out of SampleResult.getAssertionResults() method and it doesn't display anything in case of HTTP request failure.
Any idea how to get the stacK trace?
I figured it out. SampleResult has one more method called getResponseDataAsString(). This method returns the response message. In case of error it contains the error message.

Resources