JSon seralization error with Web Api - asp.net-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;

Related

Spring Controller does nothing

Greeting my dear fellows
I would appreciate some help since I've been 2 days googling to find out why my code is not working. My webapp is Spring running in a Weblogic Server under Eclipse. Btw, apologies for my spelling (I am not native English speaker)
Straight from my webapp, the following controller works flawless
#RequestMapping(value = "/sendFile")
public ModelAndView vistaEnvioFicheros() throws myCustomException {
ModelAndView model = null;
try {
getLog().debug("Setting model for sending a file");
model = new ModelAndView("/content/sendFileWeb");
} catch (Exception ex) {
getLog().error("Shxx happens: ", ex);
throw new myCustomException(ex.getMessage(), ex);
}
return model;
}
This controller loads a jsp file with a file browser button and a file upload button which works great too.
So when I click on the upload button the following controller triggers:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public Object subirFichero(#RequestParam(value = "file") MultipartFile file) throws myCustomException {
ModelAndView model = null;
if (file.isEmpty()){
try {
getLog().debug("File is empty");
model = new ModelAndView("/content/errorWeb");
} catch (Exception ex) {
getLog().error("Shxx happens again ", ex);
throw new myCustomException(ex.getMessage(), ex);
}
return model;
}
...
}
Problem is: when I upload empty file, errorWeb jsp file should be shown in my web browser, however nothing happens. If I debbug the controlles I can see the code runs propperly until return model sentence nonetheless errorWeb jsp file is not loaded
Could anyone give me a hint about why first controller loads it jsp view but second controller doesn't. Also I don't get a single error message in any console or whatever
Thank you very much
Ok, I got it solved! This was just a newbie thing (I am a newbie web developper).
The problem was in the client side, where my webapp was sending the request thay triggers the second controller, not by an standard href o after a submit (or whatever), but by a custom javascript function.
This custom javascript function firstly validates the file and then uploads it to the server. After that client side code stops listening the response from the server. That's why the new ModelAndView is ignored.
Thank you for your time to all of you who read the post

How to properly handle Google SDK errors in Google App Script

I am writing a google web app which uses the Admin Directory a lot. However I was wondering how the error handling should be done since I do not get a proper error object back when a request to the api fails.
Example: I want to check if a custom schema exists and if not I want to do something else:
try{
var resp = AdminDirectory.Schemas.get("129898rgv", "someCustomSchema");
}catch(err){
// if schema does not exist do this
schemaNotExistFunction();
Logger.log(err);
}
Unfortunately I do not even get the http status code back from the err. Is there another way to handle errors in Google Apps Script?
Instead of
Logger.log(error)
use
Logger.log('%s, %s',error.message, error.stack);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error for a complete list of Error instance properties
The above because Logger.log parses the parameter as string. When you pass an error object error.name is logged, by the other hand by using
Example
Running the following code in an standalone project using the new runtime (V8) will log a couple of messages.
function myFunction() {
try{
SpreadsheetApp.getUi();
} catch (error) {
Logger.log(error);
Logger.log('%s, %s', error.message, error.stack);
}
}
Another alternative is to use console.log instead of Logger.log
function myFunction() {
try{
SpreadsheetApp.getUi();
} catch (error) {
console.log(error);
console.log('%s, %s', error.message, error.stack);
}
}

Where is the exception information when I return InternalServerError from a Web Api?

I'm calling one Web Api (.NET Framework) from another (.NET Core). If the called one returns an InternalServerError(exception), how do I access that exception from the calling code?
The called one does this:
public IHttpActionResult GetAccountTransactions()
{
try
{
// do some stuff
}
catch (Exception e)
{
return InternalServerError(e);
}
}
The calling one does this:
HttpResponseMessage response = await client.GetAsync(url);
...but when I add the response to the watch window in Visual Studio, I can't find the exception information.
Using Fiddler, I confirmed that the exception was included in the response body but it took some work to extract it.
See How can I retrieve passed exception from HttpResponseMessage(HttpStatusCode, Exception)
I tested this answer posted there with .NET Framework, but not with .NET Core.
if(!response.IsSuccessStatusCode){
HttpError error = response.Content.ReadAsAsync<HttpError>().Result;
}

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

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