BreezeJS - server validation changed in version 1.4.4 - validation

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;
}

Related

Exception handling in Spring to align with Front-End

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 ?

SOAP UI response

I want to view the response for the below method in SOAP UI. The url would be as below to call the accountDetails(..) method in SOAP UI to check the response.
http://localhost:8080/AccountInfo/rest/account/0003942390
#RequestMapping(value = /accountDetails/{accNum}, method = RequestMethod.GET)
public void accountDetails(#PathVariable final String accNum)
{
final boolean accountValue = service.isAccountExists(accNum);
if (!accountValue )
{
throw new Exception();
}
}
The method is executed correctly but the response i'm getting in SOAP UI is 404.
accountDetails(..) method return type is void, so do i need to set any extra parameters when i have to check the response for the method in SOAP UI with void return type to show success message.
Below is the message shown in SOAP UI:
HTTP/1.1 404 /AccountInfo/WEB-INF/jsp/account/0003942390/accountInfo.jsp
Server: Apache-Coyote/1.1
Is the exception thrown? If yes, how does the framework handle the exception?
Your method doesn't return anything - see here. Based on the RESTful nature of the URL it seems the method should return something like an AccountDetail. However, if you really just want to see the 200 then just return something like a non-null String.

JSon seralization error with Web Api

I was getting a self referenceing loop error "Self referencing loop detected for property 'ApplicationInstance' with type 'ASP.global_asax'" returned from a PUT call to a web api.
I added this to the web api config:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
Now I get a different error:
"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8
InnerException":ExceptionMessage":"Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)...
Per suggestion, I added the ".ReferenceLoopHandling.Ignore;" config. This fixesd the loop error, but not the 'can't read value' error.
I am having some trouble finding a cure for this one.
EDIT - Error is gone. I am hesitant to say yet if it is fixed, because I am not yet sure why the error was there in the first place. I made the error leave by changing my Put code in the web api. It was:
[HttpPut]
public IHttpActionResult Put([FromBody]RecipientDTO recipient)
{
try
{
repo.SaveUpdatedRecipient(recipient);
return Ok(this.GetById(recipient.RecipKey));
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
and is now:
[HttpPut]
public HttpResponseMessage Put([FromBody]RecipientDTO recipient)
{
try
{
repo.SaveUpdatedRecipient(recipient);
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
ex.ToString();
//ValidationMethods.GetDbValidationExceptions(ex);
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
I am still working on the error handling portion, but at least the error is gone and the data is saved. I will update when I find out more. Any input is welcome.
To solve the issue add the below line of code to WebApiConfig.cs file in your webapi project
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

JUnit needs special permissions?

My builds have been failing due to some of the integration tests I've been running. I'm stuck on why it won't work. Here is an example of the output:
I'm using Maven to first build, then it calls the JUnit tests. I'm seeing this 401 Unauthorized message in every single test, and I believe that's what is causing the builds to fail. In my mind, this means there are some permissions / authentication parameters that need to be set. Where would I go about doing this in JUnit?
Edit
#Test
public void testXmlHorsesNonRunners() throws Exception {
String servletUrl = SERVER + "sd/date/2013-01-13/horses/nonrunners";
Document results = issueRequest(servletUrl, APPLICATION_XML, false);
assertNotNull(results);
// debugDocument(results, "NonRunners");
String count = getXPathStringValue(
"string(count(hrdg:data/hrdg:meeting/hrdg:event/hrdg:nonrunner/hrdg:selection))",
results);
assertEquals("non runners", "45", count);
}
If you can, try to ignore the detail. Effectively, this is making a request. This is a sample of a test that uses the issueRequest method. This method is what makes HTTP requests. (This is a big method, which is why I didn't post it originally. I'll try to make it as readable as possible.
logger.info("Sending request: " + servletUrl);
HttpGet httpGet = null;
// InputStream is = null;
DefaultHttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
doFormLogin(httpclient, servletUrl, acceptMime, isIrishUser);
httpGet = new HttpGet(servletUrl);
httpGet.addHeader("accept", acceptMime);
// but more importantly now add the user agent header
setUserAgent(httpGet, acceptMime);
logger.info("executing request" + httpGet.getRequestLine());
// Execute the request
HttpResponse response = httpclient.execute(httpGet);
// Examine the response status
StatusLine statusLine = response.getStatusLine();
logger.info(statusLine);
switch (statusLine.getStatusCode()) {
case 401:
throw new HttpResponseException(statusLine.getStatusCode(),
"Unauthorized");
case 403:
throw new HttpResponseException(statusLine.getStatusCode(),
"Forbidden");
case 404:
throw new HttpResponseException(statusLine.getStatusCode(),
"Not Found");
default:
if (300 < statusLine.getStatusCode()) {
throw new HttpResponseException(statusLine.getStatusCode(),
"Unexpected Error");
}
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
Document doc = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
// debugContent(instream);
doc = documentBuilder.parse(instream);
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpGet.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
}
}
return doc;
} finally {
// Release the connection.
closeConnection(httpclient);
}
I notice that your test output shows HTTP/1.1 500 Internal Server Error a couple of lines before the 401 error. I wonder if the root cause could be hiding in there. If I were you I'd try looking for more details about what error happened on the server at that point in the test, to see if it could be responsible for the authentication problem (maybe the failure is in a login controller of some sort, or is causing a session to be cancelled?)
Alternately: it looks like you're using the Apache HttpClient library to do the request, inside the issueRequest method. If you need to include authentication credentials in the request, that would be the code you'd need to change. Here's an example of doing HTTP Basic authentication in HttpClient, if that helps. (And more examples, if that one doesn't.)
(I'd second the observation that this problem probably isn't specific to JUnit. If you need to do more research, I'd suggest learning more about HttpClient, and about what this app expects the browser to send. One possibility: use something like Chrome Dev Tools to peek at your communications with the server when you do this manually, and see if there's anything important that the test isn't doing, or is doing differently.
Once you've figured out how to login, it might make sense to do it in a #Before method in your JUnit test.)
HTTP permission denied has nothing to do with JUnit. You probably need to set your credentials while making the request in the code itself. Show us some code.
Also, unit testing is not really meant to access the internet. Its purpose is for testing small, concise parts of your code which shouldn't rely on any external factors. Integration tests should cover that.
If you can, try to mock your network requests using EasyMock or PowerMock and make them return a resource you would load from your local resources folder (e.g. test/resources).

Google plus api not valid access token exception

I'm working with Google+ API and here's what I got. I know that the access token may become invalid in case of the user uninstalling App or de-authorizing it. But I couldn't find how to handle that case. Is it going to throw an exception? If so, what exact exception (maybe someone knows the code)?
I thought that it might be possible to get an http error code like 404 (unauthorized)? If it is, how do I get it?
Here is some code:
try {
$me = $plus->people->get('me')
} catch (Exception $e) {
// Maybe do something with the error code from $e->getCode();
}
Or check the code obtained from I don't know where:
if($code == 401) {
throw new Exception('Expired access token detected. Mailing to admin.', 0);
}
You can get the http status from $e->getCode()

Resources