Exception handling in Spring to align with Front-End - spring

Gone through the link https://www.mkyong.com/spring-boot/spring-boot-ajax-example/
and observed the following
Don't type any name and hit search button - Bad Request - It Comes to Error Function of Ajax - User Can't be Empty - Form Validation. Ajax response is error in this case.
Type "Raju" in name field and hit search button - Business Error - Returned with Success Function. Ajax response is success in this case.
Assume i have thrown a run time exception in getSearchResultViaAjax() as below
AjaxResponseBody result = new AjaxResponseBody();
if(1==1) {
throw new RuntimeException();
}
The same Ajax error block is getting called.
error: function (e) {
var json = "<h4>Ajax Response Error </h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR pp : ", e);
$("#btn-search").prop("disabled", false);
}
So for Bad Request and Any Exception which comes Out side the box comes in error block
Which would be the right approach in the following ? If both of them is incorrect, help me with the best practice
Approach One
Throw form validation errors as as Ajax Response is ERROR with failure message to display
Throw Business validation errors as Ajax Response is SUCCESS with failure message to display
Throw any other exception as Ajax Response is ERROR with failure message to display
OR
Approach Two
Throw form validation error as Ajax Response is ERROR with failure message to display ('User Field is Empty')
Throw Business validation errors as Ajax Response is FAILURE with failure message to display ('User Name doesn't exist')
Throw any other exception as Ajax Response is ERROR with failure message to display
What would be the best approach or best practice ?

Related

Error Message in Parse.com CloudCode - parse update?

My Cloud Code below was working fine until recently. Now I'm getting an error message (see below) but don't know why. My guess is Parse updated some of their API, but I do not know for sure. Also, I'm not a JavaScript person and therefore are hoping for some insight. Does somebody have a hint for me?
Parse.Cloud.define("setUserAnswersForQuestionIds", function(request, response) {
//the following line creates the error
var userId = request.user.get("userId"),
endpointURL = constants.apiURL2 + userId + "/preferences";
...
Here is the error message
{
"code": 141,
"error": "TypeError: Cannot call method 'get' of null\n at vivanda_api.js:241:29"
}
You're sending the request from a non-active user session: i.e. no one is logged in, thus request.user is null.

How to handle empty JSONObject in Processing?

Hi I am using loadJSONObject function in Processing IDE to receive a JSON Object from a URL.
Following is my code:
JSONObject jsonUserLocations = loadJSONObject("http://smrt.utd.sg/eLocation/getLocs.php?userId="+usrID+"&sTime="+strtTime+"&eTime="+endTym);
This code works when the php returns some data (for some users).
The problem occurs when it doesn't return any data. (php doesn't return any data when there is no data, browser shows a blank page. this means user has no location data)
At this instance, the Processing IDE gives me an error saying;
a jsonobject text must begin with {
My question is how can I handle empty JSON Object in this type of situation? I need to skip if this is empty and request data for next user. Your help is much appreciated.
Thanks,
Hasala
Edit:
This is sample json object I receive when there is data.
{"locations":[{"latitude":"1.3809274","longitude":"103.7654596","startTime":"1421918587868","duration":"0","accuracy":"30"},{"latitude":"1.3805307","longitude":"103.7661015","startTime":"1421941711737","duration":"0","accuracy":"45"},{"latitude":"1.3805304","longitude":"103.7660959","startTime":"1421942011727","duration":"0","accuracy":"45"},{"latitude":"1.3799822","longitude":"103.7658037","startTime":"1421942311835","duration":"0","accuracy":"82.5"}],"success":1}
You have two options:
You could read the String form the URL first, and if it's blank, don't bother with the parsing.
Or you could just catch the exception that Processing throws:
try{
JSONObject jsonUserLocations = loadJSONObject("http://smrt.utd.sg/eLocation/getLocs.php?userId="+usrID+"&sTime="+strtTime+"&eTime="+endTym);
}
catch(JSONException e){
e.printStackTrace();
//json was blank, do something else
}

BreezeJS - server validation changed in version 1.4.4

I've updated breezejs from version 1.4.1 to 1.4.4. For server-side validation, I was handling the AfterSaveEntitiesDelegate on the ContextProvider and throwing EntityErrorsException().
In the release notes I read:
The Breeze WebApi response to any SaveChanges operation that has
validation errors now returns a 403 status code, instead of a 200.
This has no effect on any Breeze code but will be noticeable to anyone
watching Breeze's network traffic.
However, the new 403 error does not have any details about the validation error or any inner exceptions that would indicate it is a validation error. Instead the error is: "Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details." There is no "Response" property. Also, now my client-side code no longer "understands" this error.
Turns out that this exception is not intended to be caught and wrapped into an HttpResponseMessage. My code for the BreezeController SaveChanges() api was:
try
{
return Request.CreateResponse(HttpStatusCode.OK, _commDataService.SaveChanges(pSaveData, shouldValidate));
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
}
This was returning the right exception but with the wrong status code (500 instead of 403 as expected by updated breezejs client code.
I added a new catch to pass along the breeze-constructed response message:
catch (System.Web.Http.HttpResponseException responseException)
{
//todo: logger call.
return responseException.Response;
}

KendoUI datasource error event not raised on post with http 500 error

I have a datasource with error handler defined as below. In the code I am intentionally causing an error on post and the server is returning 500 plus the json data, but the error event is not being raised on post. It does fire on the read event. See http://www.ageektech.com/simplyfundraising Open your browser debugger, refresh the page, click edit change any value, click update. Need help figuring out why the error event is not triggered.
Thanks,
Dan
schema : {
model : myModel,
data : "__ENTITIES",
errors: function(e) {
debugger;
// var xhr = e.xhr;
// var statusCode = e.status;
// var errorThrown = e.errorThrown;
//alert(JSON.parse(e.responseText).error.innererror.message);
return e.errors;
}
This is not the way to subscribe to the error event of the DataSource. The schema.errors setting is used for a different purpose.
Schema.errors should contain the name of the JSON field that contains error messages.
e.g.
schema: { errors: "Errors" }
For when you are returning JSON like:
{ "Errors": "Stuff went wrong" }

MVC Generic error view and Ajax Post and error code 500

I have set up an mvc app with an _error.cshtml that is set to catch exceptions I throw in the controller.
I also have a few ajax posts on some pages that checks for errors and then it does something else.
On the server, I have a filter on all exceptions and then check if it is an ajax request and return something that can be deserialized on the client. The problem is that if I do not set the post response status code to 500 then ajax will not see this error and I can't show a nice message. If I set the status to 500 I get the default IIS error message stating something happened on the server.
I would like to handle some errors on the page in the ajax results but maintain the generic error handling. Is this an IIS setting to allow custom 500 message per site? The web.config Custom Error On|Off makes no difference in my case.
The filter you have on all exceptions that is checking if its an ajax request, is that a filter made on your own?
I had a slightly similar issue, and I had to make sure the flag TrySkipIisCustomErrors was set as true in order to avoid the standard IIS error.
This flag is located on the Response object of the HttpContext.
This is also done by the standard HandleError filter, pay attention to the last line in its implementation of the OnException method:
public virtual void OnException(ExceptionContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (filterContext.IsChildAction) {
return;
}
// If custom errors are disabled, we need to let the normal ASP.NET exception handler
// execute so that the user can see useful debugging information.
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled) {
return;
}
Exception exception = filterContext.Exception;
// If this is not an HTTP 500 (for example, if somebody throws an HTTP 404 from an action method),
// ignore it.
if (new HttpException(null, exception).GetHttpCode() != 500) {
return;
}
if (!ExceptionType.IsInstanceOfType(exception)) {
return;
}
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult {
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}

Resources